我有以下代码:
<mat-form-field>
<mat-label>Element Parent:</mat-label>
<input type="text" matInput
(input)="getHierarchyService.filterFlatHierarchy($event)"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete"
[displayWith]="displayLabel">
<mat-option class="mat-option-height" (click)="GetHierarchyLevel()"
*ngFor="let option of getHierarchyService.filteredHierarchyFlatData"
[value]="option">
{{returnSemiStringPath(option.Path)}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
函数returnSemiStringPath从输入返回一个缩短的字符串:
returnSemiStringPath(path: string) {
let newPathArray = path.split('/')
return `${newPathArray[0]}/${newPathArray[1]}.....
${newPathArray[newPathArray.length-1]}/${newPathArray[newPathArray.length-2]}`
}
我想在第一部分和新字符串的最后部分添加样式(添加颜色)。
我想从我的ts文件中“创建”html元素,并使用我想要的样式将它们附加到此函数中。但我不知道如何以角度来实现这一目标。
*我知道这个功能,因为它可能是一个不好的做法,我会把它变成一个角度管道,以便在它工作后更有效率。
感谢大家的帮助!
根据我的理解,您希望添加返回字符串的第一个和最后一部分的颜色。用户Angular HTML绑定,像这样..
<mat-option class="mat-option-height" (click)="GetHierarchyLevel()"
*ngFor="let option of getHierarchyService.filteredHierarchyFlatData"
[value]="option">
<span [innerHTML]="returnSemiStringPath(option.Path)"></span>
</mat-option>
returnSemStringPath函数会像这样被修改
returnSemiStringPath(path: string) {
let newPathArray = path.split('/')
return `<span class='redcolor'>${newPathArray[0]}</span>/${newPathArray[1]}.....
${newPathArray[newPathArray.length-1]}/<span class='bluecolor'>${newPathArray[newPathArray.length-2]}</span>`}
组件装饰器看起来像这样..
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styles: ['.redcolor { color: red; }', '.bluecolor{color:blue;}'],
encapsulation: ViewEncapsulation.None,
})
感谢名单。
我认为这段代码可以帮助你:
.TS
returnSemiStringPath(path: string) {
const newPathArray = path.split('/');
return newPathArray;
}
html的
<div class="hero">
<div *ngFor="let hero of returnSemiStringPath('https://stackoverflow.com/questions/53997450/how-to-add-style-to-a-string-returned-from-a-function-called-from-the-html-file')">
<span>{{hero}}</span>
</div>
</div>
如果你想要你可以改变* ngFor中的div块来跨越并移除span是哪里是英雄。
的CSS
.hero div:first-child {
color: red;
}
.hero div:last-child{
color: red;
}