GJAIN
GJAIN

Reputation: 133

Add dynamic html content angular 4

I am trying to achieve dynamic template creation for child component. Given below is the method that sets the template content and load child component for template creation.

Parent Component

 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;
 }

Parent template

<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>

Child Component

@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) {
        }
    }
}

But the output generated by the above code has only text present in html string ("testing form" and "cancel") it does not generate any form and input element present in html string (form and input elements).

I am trying to achieve what we do with $compile in angular 1.

Upvotes: 2

Views: 3332

Answers (1)

Narm
Narm

Reputation: 10864

What you'r trying to do requires you to create a dynamic component, using [innerHTML} will not work for your use case.

If you check out the S.O. answer here it contains a stackblitz example that will demonstrate what you need to do.

Angular: How to use reactive forms in a dynamic component

Upvotes: 1

Related Questions