angular dom操作
ElementRef获取不同平台视图native元素封装在ElementRef实例的nativeElement属性中,ElementRef获取的是整个组件实例可以用ViewChild装饰器获取匹配的ElementRef实例
@Component({
template:`
<div #customizeDiv class="customizeDiv"></div>
`
})
export class AppComponent implements AfterViewInit{
@ViewChild('customizeDiv') customizeDiv:ElementRef;
constructor(
private elementRef:ElementRef,
private r2:Renderer2
){
}
ngAfterViewInit(){
// this.customizeDiv.nativeElement.style.backgroundColor = 'red';
// this.elementRef.nativeElement.querySelector('.customizeDiv').style.backgroundColor = 'red';
// 使用r2渲染的目的是为了解除终端的耦合
// this.r2.setStyle(this.customizeDiv.nativeElement,"backgroundColor","red");
}
}
Renderer2 API
export abstract class Renderer2 {
abstract createElement(name: string, namespace?: string|null): any;
abstract createComment(value: string): any;
abstract createText(value: string): any;
abstract setAttribute(el: any, name: string, value: string,
namespace?: string|null): void;
abstract removeAttribute(el: any, name: string, namespace?: string|null): void;
abstract addClass(el: any, name: string): void;
abstract removeClass(el: any, name: string): void;
abstract setStyle(el: any, style: string, value: any,
flags?: RendererStyleFlags2): void;
abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void;
abstract setProperty(el: any, name: string, value: any): void;
abstract setValue(node: any, value: string): void;
abstract listen(
target: 'window'|'document'|'body'|any, eventName: string,
callback: (event: any) => boolean | void): () => void;
}
ViewContainerRef 创建和管理内嵌视图或组件视图,通过 ViewContainerRef 实例,我们可以基于 TemplateRef 实例创建内嵌视图,并能指定内嵌视图的插入位置,也可以方便对视图容器中已有的视图进行管理。
@Component({
selector: "hello-world",
template: `
<h3>Hello World</h3>
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
`
})
export class HelloWorldComponent implements AfterViewInit {
@ViewChild("tpl") tplRef: TemplateRef<HTMLElement>;
@ViewChild("tpl", { read: ViewContainerRef }) tplVcRef: ViewContainerRef;
ngAfterViewInit(): void {
this.tplVcRef.createEmbeddedView(this.tplRef);
}
}
ngTemplateOutlet 指令用于标识指定的 DOM 元素作为视图容器,然后自动地插入设定的内嵌视图,比ViewContainerRef简单
Component({
selector: "hello-world",
template: `
<ng-container *ngTemplateOutlet="tpl"></ng-container>
<ng-template #tpl>
<span>hello world</span>
</ng-template>
`
})
export class TplComponent{}
网友评论