根据文档,我理解的是templateRef可以通过以下方式使用
通过放置在
<ng-template>
元素*(或指令)上的指令 以*
为前缀,并为此嵌入视图设置TemplateRef
使用the注入*指令的构造函数TemplateRef
令牌
我有以下组件&amp;像这样的指令
import { Component, ViewChild, ComponentRef, ViewContainerRef, AfterContentInit, ElementRef, TemplateRef } from '@angular/core';
@Component({
selector: 'my-app',
template:
`
<div appMyDirective>
<form #frm='ngForm' (ngSubmit)='formSubmit(frm)'>
<div>
<div>
<input type='text' name='firstname' placeHolder='first name' ngModel required/>
</div>
<div>
<input type='text' name='lastname' placeHolder='last name' ngModel required/>
</div>
<ng-template appMyDirective>
<div>smoke on the water</div>
</ng-template>
</div>
<div>
<input type='submit' value='submit'/>
</div>
</form>
</div>
`
})
export class AppComponent implements AfterContentInit {
node: string;
constructor(private viewContainerRef: ViewContainerRef) { }
ngAfterContentInit() {
let elementRef = this.viewContainerRef.element;
const tmp = document.createElement('div');
const el = elementRef.nativeElement.cloneNode(true);
console.log(elementRef)
console.log(this.viewContainerRef)
tmp.appendChild(el);
this.node = tmp.innerHTML;
}
}
指令
import { Directive, ViewContainerRef, AfterContentInit, TemplateRef, ElementRef } from '@angular/core';
@Directive({
selector: '[appMyDirective]'
})
export class MyDirectiveDirective implements AfterContentInit {
constructor(private viewContainer: ViewContainerRef, private element: ElementRef, private template: TemplateRef<any>) { }
ngAfterContentInit() {
debugger;
console.log(this.viewContainer);
console.log(this.element);
}
}
但我仍然无法使用templateRef,我收到的错误是这样的:
任何人都可以解释我如何使用angular templateRef