Angular 4 |模板绑定通过innerHTML,组件变量不可访问(damContentRoot就是这种情况)

时间:2017-11-28 12:12:53

标签: angular

我们必须从API绑定模板,然后将damContentRoot声明为组件中的公共变量。但它没有得到反映。

   @Component({
    selector: 'app-plans',
    template: '<div *ngIf="pageTemplate" [innerHTML]="pageTemplate | safeHtml"></div>'
})
export class PlansComponent {
   public pageTemplate: string;
   public damContentRoot: string;
   public ngOnInit(): void {
   this.damContentRoot = "abcde";
   this.pageTemplate = `<div>Goog <span [innerHtml]="damContentRoot"></span>
                <span [innerHtml]="'<p>Yahoo</p>'"></span></div>`;

   }
}

damContentRoot不会更新。尝试动态组件,但随后damContentRoot变得超出该组件的范围变量。

2 个答案:

答案 0 :(得分:2)

您可以创建自己的指令来执行此操作:

<强> compile.directive.ts

              @Directive({
                selector: '[compile]'
            })
                export class CompileDirective implements OnChanges {
            @Input() compile: string;
              @Input() compileContext: any;

                compRef: ComponentRef<any>;

                constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}

                ngOnChanges() {
                    if(!this.compile) {
                        if(this.compRef) {
                            this.updateProperties();
                            return;
                        }
                        throw Error('You forgot to provide template');
                    }

                    this.vcRef.clear();
                    this.compRef = null;

                    const component = this.createDynamicComponent(this.compile);
                    const module = this.createDynamicModule(component);
                    this.compiler.compileModuleAndAllComponentsAsync(module)
                        .then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
                            let compFactory = moduleWithFactories.componentFactories.find(x => x.componentType === component);

                            this.compRef = this.vcRef.createComponent(compFactory);
                            this.updateProperties();
                        })
                        .catch(error => {
                            console.log(error);
                        });
                }

                updateProperties() {
                    for(var prop in this.compileContext) {
                        this.compRef.instance[prop] = this.compileContext[prop];
                    }
                }

                private createDynamicComponent (template:string) {
                @Component({
                        selector: 'custom-dynamic-component',
                        template: template,
                    })
                    class CustomDynamicComponent {}
                    return CustomDynamicComponent;
                }

                private createDynamicModule (component: Type<any>) {
                @NgModule({
                        // You might need other modules, providers, etc...
                        // Note that whatever components you want to be able
                        // to render dynamically must be known to this module
                        imports: [CommonModule],
                        declarations: [component]
                    })
                    class DynamicModule {}
                    return DynamicModule;
                }
            }

<强>用法: -

            import { Component, Input, NgModule } from '@angular/core'
            import { BrowserModule } from '@angular/platform-browser'

            import { CompileDirective } from './compile.directive';

            @Component({
                selector: 'my-app',
                template: `
            <div class="product"><ng-container *compile="template1; context: this"></ng-container></div>
            `,
            })
            export class App {
                damContentRoot = "abcde";
              @Input() template1: string = `<div>Goog <span [innerHtml]="damContentRoot"></span><span [innerHtml]="'<p>Yahoo</p>'"></span></div>`;
            }

            @NgModule({
                imports: [ BrowserModule ],
                declarations: [ App, CompileDirective ],
                bootstrap: [ App ]
            })
            export class AppModule {}
            }

Plunker

答案 1 :(得分:0)

pageTemplate 是一个字符串,但您在模板中将其视为布尔值,如果您想如上所述使用它,则应将其转换为bollean值。

或在 ngIf

中检查相应的值
template: '<div *ngIf="pageTemplate === 'yourStringvalue'" [innerHTML]="pageTemplate | safeHtml"></div>'