[英]Angular use parent scope in ng-container
I have a grid component with some configs.我有一个带有一些配置的网格组件。
I want to define thead and tbody while I'm using a component.我想在使用组件时定义 thead 和 tbody。 This is my component这是我的组件
@Component({
selector: 'tcs-grid',
templateUrl: './tcs-grid.component.html',
styleUrls: ['./tcs-grid.component.scss']
})
export class TcsGridComponent implements OnInit {
data : any;
//some configs
}
This is Html template这是 Html 模板
<table datatable class="table tablesorter" [dtOptions]="dtOptions">
<ng-content>
</ng-content>
</table>
Now I want to use it like this现在我想像这样使用它
Usage:用法:
<tcs-grid>
<thead >
<tr>
<th width="50px" >Row</th>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody *ngIf="data?.length != 0">
<tr *ngFor="let person of data;index as i">
<td>{{ i + startPoint }}</td>
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
</tr>
</tbody>
</tcs-grid>
I know with event emitter you can output data.我知道使用事件发射器可以输出数据。 I want to know if there is a better way to access the data in the grid component(parent).我想知道是否有更好的方法来访问网格组件(父)中的数据。
Thanks谢谢
I find the solution by using ng-template, you can create partial templates!我通过使用ng-template找到解决方案,您可以创建部分模板!
Don't forget to add context in order to bind your parent scope variables不要忘记添加上下文以绑定父作用域变量
Template:模板:
<table datatable class="table tablesorter" [dtOptions]="dtOptions">
<ng-container *ngTemplateOutlet="layoutTemplate; context: {persons: data}" >
</ng-container>
</table>
Component:成分:
export class TcsGridComponent implements OnInit {
@ContentChild(TemplateRef,null)
@Input() layoutTemplate: TemplateRef<any>;
data : any;
ngAfterContentInit()
{
//your code
}
}
Usage:用法:
<tcs-grid>
<ng-template let-persons="persons">
<thead >
<tr>
<th width="50px" >Row</th>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody *ngIf="persons?.length != 0">
<tr *ngFor="let person of persons;index as i">
<td>{{ i + startPoint }}</td>
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
</tr>
</tbody>
</ng-template >
</tcs-grid>
You can access variables in parent scope by naming let-yourvariablename.您可以通过命名 let-yourvariablename 来访问父作用域中的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.