我有一个包装表单控件的组件。这为每个控件添加了可重用的代码,但为了简单起见,假设它所做的只是添加一个标签:
应用程序组件:
<app-wrapper labelText="First Name">
<input type="text" >
</app-wrapper>
包装器.组件:
<div style="border:thin solid; padding:10px">
<label>{{labelText}}</label>
<ng-content></ng-content>
</div>
export class WrapperComponent {
@Input() labelText;
}
我想将包装器改为@Directive,以便进一步减少表单中的 HTML 数量,但我无法完全理解它的工作原理。我的想法是这样的:
应用程序组件:
@Component({
selector: 'my-app',
template: `
<input type="text" wrapper labelText="First Name">
<input type="text" wrapper labelText="Last Name" >
<ng-template #tpl>
<div style="border:thin solid; padding:10px">
<label>{{labelText}}</label>
<ng-content></ng-content>
</div>
</ng-template>`
})
export class AppComponent {
@ViewChild('tpl', {read:TemplateRef}) tpl
constructor(private service: TemplateService) { }
ngAfterViewInit() {
this.service.template = this.tpl;
}
}
包装器.dir
@Directive({
selector: '[wrapper]'
})
export class WrapperDirective {
@Input('labelText') labelText;
constructor(
private vc:ViewContainerRef,
private service:TemplateService) { }
ngAfterViewInit() {
of(null).pipe(
delay(1)).subscribe(() => {
let tpl = this.service.template;
this.vc.createEmbeddedView(this.service.template)
})
}
}
不幸的是,我相信这会将标签放在输入标签之后而不是前面。怎么插在前面?
另一个问题是:如何访问模板中的#labelText?