详解Angular 自定义结构指令(2)

// ... @Component({ selector: 'ng-component-outlet-complete-example', template: ` <ng-container *ngComponentOutlet="CompleteComponent; injector: myInjector; content: myContent"></ng-container>` }) class NgTemplateOutletCompleteExample { // This field is necessary to expose CompleteComponent to the template. CompleteComponent = CompleteComponent; myInjector: Injector; myContent = [[document.createTextNode('Ahoj')], [document.createTextNode('Svet')]]; constructor(injector: Injector) { this.myInjector = ReflectiveInjector.resolveAndCreate([Greeter], injector); } }

4. 创建结构指令

也想不出来一个什么好例子,抄一个例子过来:

// uless.directive.ts import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[exeUnless]' }) export class UnlessDirective { @Input('exeUnless') set condition(newCondition: boolean) { // set condition if (!newCondition) { this.viewContainer.createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { } } import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h2 *exeUnless="condition">Hello, Semlinker!</h2> `, }) export class AppComponent { condition: boolean = false; } // app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h2 *exeUnless="condition">Hello, Semlinker!</h2> `, }) export class AppComponent { condition: boolean = false; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfpgs.html