angglar 6.xにおけるngTemplateOutletコマンドの使用例
2769 ワード
アングラーを使用して開発する場合、属性を組み合わせてコンポーネント内部に値を伝える方式で、必要なものを完全に満たすことができない場合があります。たとえば、共通のコンポーネントを書いていますが、あるテンプレートがこの共通のコンポーネントを使用する場合、その内部にラベルの内容を追加する必要があります。nTemplateOutletコマンドを利用してコンポーネントにコンテンツを入力することができます。
ngTemplateOutletコマンドはangglarjsの中のng-transcludeに似ています。vuejsの中のslatt.
ngTemplateOutletは構造的命令であり、TemplateRefタイプをバインドする必要がある例である。
使用方法は以下の通りです容器コンポーネント:ap-content に転送されたコンテンツコンポーネント:ap-ness ted-component ap-contentコンポーネントは、TemplateRefタイプの入力属性templateRefを受信し、テンプレート内でそれをngTemplateOutletコマンドに結びつけ、コンポーネントがtemplateRef属性を受信すると、ngTemplateOutletコマンドの位置にレンダリングする。
上記の例では、app-contentコンポーネントtemplateRef属性のソースは、ルートコンポーネントのテンプレート内で、ap-neted-componentコンポーネントのある'ng-template'の参照を直接に((over)記号で取得して導入したものである。
実際のアプリケーションでは、このような方法に加えて、TemplateRefタイプの属性を直接コンポーネント内部で取得し、ngTemplateOutletコマンドに結びつけることもできる。
例えば、コンテナコンポーネントがモダリティボックスの場合、テンプレートを通して値を伝えられない場合には、次のような方法が使えます。
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。
ngTemplateOutletコマンドはangglarjsの中のng-transcludeに似ています。vuejsの中のslatt.
ngTemplateOutletは構造的命令であり、TemplateRefタイプをバインドする必要がある例である。
使用方法は以下の通りです
@Component({
selector: 'app',
template: `
<h1>Angular's template outlet and lifecycle example</h1>
<app-content [templateRef]="nestedComponentRef"></app-content>
<ng-template #nestedComponentRef let-name>
<span>Hello {{name}}!</span>
<app-nested-component></app-nested-component>
</ng-template>
`,
})
export class App {}
@Component({
selector: 'app-content',
template: `
<button (click)="display = !display">Toggle content</button>
<template
*ngIf="display"
*ngTemplateOutlet="templateRef context: myContext">
</template>
`,
})
export class Content {
display = false;
@Input() templateRef: TemplateRef;
myContext = {$implicit: 'World', localSk: 'Svet'};
}
@Component({
selector: 'app-nested-component',
template: `
<b>Hello World!</b>
`,
})
export class NestedComponent implements OnDestroy, OnInit {
ngOnInit() {
alert('app-nested-component initialized!');
}
ngOnDestroy() {
alert('app-nested-component destroyed!');
}
}
コードにはコンポーネント以外に二つのコンポーネントが定義されています。上記の例では、app-contentコンポーネントtemplateRef属性のソースは、ルートコンポーネントのテンプレート内で、ap-neted-componentコンポーネントのある'ng-template'の参照を直接に((over)記号で取得して導入したものである。
実際のアプリケーションでは、このような方法に加えて、TemplateRefタイプの属性を直接コンポーネント内部で取得し、ngTemplateOutletコマンドに結びつけることもできる。
例えば、コンテナコンポーネントがモダリティボックスの場合、テンプレートを通して値を伝えられない場合には、次のような方法が使えます。
@ViewChild('temp') temp: TemplateRef<any>
openDialog(){
this.dialog.open(ViewDialogComponent, {data: this.temp)
}
また、コンテナコンポーネントでは、伝達されたコンテンツのコンテキスト(上の例のapp-contentコンポーネントのmyContect属性)を定義してもよく、その中の$implicit属性はデフォルト値として定義されてもよく、伝達されたコンテンツの中で名前を変更してアクセスでき、コンテキスト内の他の属性については、let-属性名でアクセスする必要がある。以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。