【问题标题】:Add dynamic html content angular 4添加动态html内容角4
【发布时间】:2018-07-28 05:15:21
【问题描述】:

我正在尝试为子组件实现动态模板创建。下面给出了设置模板内容和加载子组件以创建模板的方法。

父组件

 setTemplate(){
        var templateString = '<form (ngSubmit)="save(form.value)" [formGroup]="form"> testing form<input type="text" id="test1" [formControlName]="test1"></div><div class="pull-right"><input type="submit" class="btn btn-success waves-effect btn-orange" value="Save"><button type="submit" (click)="closeLeaseDialog()"  class="btn waves-effect waves-light btn-secondary">Cancel</button></div>'

 this.htmlContent = templateString;
       this.loadTemplate = true;
 }

父模板

<div class="row" *ngIf="loadTemplate">
                    <div class="col col-xs-12 col-md-12 col-sm-12 form-group" id="templateContent">
                        <app-html-template [htmlTemplate]="htmlContent"></app-html-template>
                    </div>
                </div>

子组件

@Component({
    selector: 'app-html-template',
    template: '<div [innerHtml]="htmlString"></div>'
})
export class TemplateComponent implements OnInit {

    @Input() htmlTemplate: any;
    htmlString: string;

    ngOnInit():void {
        this.htmlString = this.htmlTemplate
    }

    saveLeaseAgreement() {
        console.log("this.form",this.form);
        if (this.form.valid) {
        }
    }
}

但上述代码生成的输出只有 html 字符串中存在的文本(“测试表单”和“取消”)它不会生成 html 字符串中存在的任何表单和输入元素(表单和输入元素)。

我正在努力实现我们在 Angular 1 中使用 $compile 所做的事情。

【问题讨论】:

    标签: angular angular2-template angular2-forms


    【解决方案1】:

    您尝试做的事情需要您创建一个动态组件,使用 [innerHTML} 不适用于您的用例。

    如果您查看 S.O. answer here 它包含一个 stackblitz 示例,该示例将演示您需要做什么。

    Angular: How to use reactive forms in a dynamic component

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-13
      • 2019-02-18
      • 2012-02-27
      • 2019-04-09
      • 1970-01-01
      • 2014-02-26
      • 2021-12-29
      • 2018-08-11
      相关资源
      最近更新 更多