如何在Angular4中将[(ng-model)]传递给@ViewChild?
问题描述:
我有一个内部有form
元素的组件。此表单有一个input[type="number"]
,它将用于调整iframe
元素。问题是,iframe
元素在@ViewChild
之内。如何将[(ng-model)]
输入到[width]
的iframe
里面@ViewChild
?该代码看起来是这样的:如何在Angular4中将[(ng-model)]传递给@ViewChild?
@Component({
selector: "demo-iframe",
template: `
<form (submit)="onSubmit($event)">
<input type="number" min="0" [(ngModel)]="model.px">px
<button>update px</button>
</form>
<div #placeholder></div>
`
})
export class DemoIframeCmp {
@ViewChild("placeholder", { read: ViewContainerRef }) private viewContainerRef: ViewContainerRef;
constructor (
private route: ActivatedRoute,
private router: Router,
private compiler: Compiler
) {
document.title = "Test iframe";
this.paramsSub = this.route.params.subscribe((params: IClickDemoParams) => {
document.title = `Demo iframe ${params.demoId}`;
this.buildDemo(params.demoId);
});
this.setWidth = 800;
}
private buildDemo (selector: string) {
@Component({
selector: "test-iframe",
template: `
<iframe class="iframe-demo" src="http://localhost:3000/${selector}" [width]="px"></iframe>
`
})
}
答
最简单的方法是在你的子组件来创建一个@input()getter和setter:
_yourValue;
@Input() set yourValue(val) {
this._yourValue = val;
}
get yourValue() {
return this._yourValue;
}
这会像ngModel为父母和孩子之间
答
我通过将form
放入子组件中解决了这个问题。另外,我不使用@Directive
,而是使用Angular的数据绑定行为。这样的东西,但在里面的@ViewChild
@Component({
selector: 'my-app',
template:
<form #f="ngForm" (submit)="onSubmit($event)">
<input type="number" [(ngModel)]="model.px" name="px">px
<button type="submit">adjust</button>
</form>
instant:
<iframe [width]="model.px"></iframe>
needs submit:
<iframe [width]="px"></iframe>
})
export class App {
model = {
px: 10
}
px = 0
constructor() {}
onSubmit(event: Event) {
event.preventDefault()
this.px = this.model.px
}
}
export class AppModule {}
你可以给一个快速演示?尝试它,但无法通过价值:( – ivanasetiawan
这是演示。您可以使用html符号将值传递给您的孩子:[yourValue] =“value” – Carsten