我有一个组件指令,可以将一堆请求转换成一个表。有没有办法根据父逻辑有条件地将文本(HTML 和 CSS)附加到此子组件中的指定行?
(父级):
<body>
<child-component></child-component>
</body>
( child ):
<div *ngfor = "let record in records">
<table>
<tr>
<td> Class: {{ alias }} </td>
</tr>
</table>
</div>
说明:如果我想附加或编辑别名为 foo
的行的 HTML/CSS通过 parent 的代码并显示:Class: foo (in-session)
编辑:“标签”不是指代码标签(即 <p>
),而是指附加文本。
最佳答案
您可以通过 Angular 的 @Input()
装饰器结合 Angular 中的 dynamic scss/css
类分配来提出解决方案。在您的子组件中,您可以像这样分配动态 css
`[ngClass]="{'CSS-CLASS': CONDITION-HERE,'CSS-CLASS':CONDITION-HERE}"`
在您的特定情况下,子 component.html:
<div *ngfor = "let record in records">
<table>
<tr>
<td> [ngClass]="{'foo': record==record.name=='foo'}" {{ alias }} </td>
</tr>
</table>
</div>
PS:- 您可以根据需要编辑类“foo”的条件。
在您的子 component.ts 中:
export class ChildComponent implements OnChanges {
@Input() public rercord: any[];
constructor() {
}
}
只要你想在父组件中使用子组件,只需使用以下命令:
<body>
<child-component [records]="fetchedRecords"></child-component>
</body>
内部父组件.ts:
export class ParentComponent {
public fetchedRecords: any;
constructor(public myService:MyService) {
this.myService.getValues().subscribe((rowData)=>{
this.fetchedRecords = rowData;
});
}
}
关于javascript - 如何在 Angular 2+ 中从父组件更改子组件的 HTML/CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59449908/