2017-12-22 9 views
1

나는 돔 조작을 배우기 위해 모퉁이를 돌며 templateRef와 그 메소드 createEmbeddedView에 주목했다. 이 방법에 대해 더 궁금해합니다.angular4에서 TemplateRef의 createEmbeddedView 메소드를 사용하는 방법은 무엇입니까?

@Component({ 
    selector: 'app-root', 
    template: ` 
     <ng-template #template let-name='fromContext'><div>{{name}}</ng-template> 
     <ng-container #vc></ng-container> 
    ` 
}) 
export class AppComponent implements AfterViewChecked { 
    @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>; 
    @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef; 
    constructor() { } 

    ngAfterViewChecked() { 
     const view = this._template.createEmbeddedView({fromContext: 'John'}); 
     this.vc.insert(view); 
    } 
} 

또는 당신이 할 수있는 지금 내 모든 질문은, 어떻게

@Component({ 
    selector: 'app-root', 
    template: ` 
<ng-template #template> 

</ng-template> 
    ` 
}) 
export class AppComponent implements AfterViewChecked { 
     @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;  
    constructor() { } 

    ngAfterViewChecked() { 
    this._template.createEmbeddedView('this is a embedded view') 
    } 
} 

답변

1

당신은 다음 ViewContainerRef를 통해 DOM에 해당 뷰를 첨부 createEmbeddedView 방법을 사용하여 내장 된 뷰를 만들 수있는이 방법의 createEmbeddedView을 사용하는 것입니다

ngAfterViewChecked() { 
    this.vc.createEmbeddedView(this._template, {fromContext: 'John'}); 
} 

컨텍스트는 특성을 가진 개체이고 당신은 throu 이러한 속성에 액세스 할 수 있습니다 직접 ViewContainerRef를 사용하여 뷰를 생성 gh let- 바인딩.

자세히 알아 보려면 Exploring Angular DOM manipulation techniques using ViewContainerRef을 읽고 this answer을 참조하십시오.

+0

컨텍스트 유형은 무엇입니까? 문자열입니까? 그리고 vc의 의미는 viewContainerRef입니까? –

+0

@ LijinDurairaj, 나는 대답을 –

+0

예, 나는 그것을 이해하지만, 내 질문은 당신이 또한 당신의 코드에서 언급 한 "컨텍스트"유형 무엇입니까 업데이트했습니다. 은 값 ie를 취하는 문자열입니다.

this is a dynamic element