РЕДАКТОР
Угловые компоненты, директивы, привязки событий и свойств работают только для HTML, статически добавляемого в шаблон компонента.
С помощью [innerHTML] = "..." вы можете добавить HTML в DOM, но Angular не будет заботиться о том, какой HTML он содержит, за исключением очистки.
Наилучшим вариантом является компиляция HTML с шаблоном компонента во время выполнения.
Сказав это, я создал демонстрационное приложение по ссылкам, упомянутым в конце этого поста. Это будет работать для вашего требования
https://stackblitz.com/edit/dynami-template-ionic
код ниже
home.ts
import {Compiler, Component, NgModule, OnInit, ViewChild,
ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class App implements OnInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private compiler: Compiler) {}
section={}
ngOnInit() {
this.addComponent(`<p>Sed ut perspiciatis unde omnis <input type="text" [(ngModel)]="section.answer1" name="answer1"/> sit voluptatem accusantium doloremque laudantium.</p><p>Totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt <input type="text" [(ngModel)]="section.answer2" name="answer2"/>`,
{
section:this.section,
increaseCounter: function () {
this.counter++;
}
}
);
}
submitAnswers(answers){
console.log(answers);
}
private addComponent(template: string, properties: any = {}) {
@Component({template})
class TemplateComponent {}
@NgModule({imports: [ FormsModule ],declarations: [TemplateComponent]})
class TemplateModule {}
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
const component = this.container.createComponent(factory);
Object.assign(component.instance, properties);
// If properties are changed at a later stage, the change detection
// may need to be triggered manually:
// component.changeDetectorRef.detectChanges();
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h1>Dynamic template:</h1>
<h2>Workbook</h2>
<form (ngSubmit)="submitAnswers(section)">
<div #container></div>
<h3>This input below is hard coded in the view and works perfectly. Inputs from string are ignored.</h3>
<input type="text" [(ngModel)]="section.answer3" name="answer3">
<br />
<p><em>** Answers are logged in console **</em></p>
<button ion-button type="submit" block>Submit Answers</button>
</form>
</ion-content>
Ссылки :
Как я могу использовать / создать динамический шаблон для компиляции динамического компонента с Angular 2.0?
https://stackoverflow.com/a/39507831/6617276
https://stackoverflow.com/a/46918940/6617276