如何在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为父母和孩子之间

+0

你可以给一个快速演示?尝试它,但无法通过价值:( – ivanasetiawan

+0

这是演示。您可以使用html符号将值传递给您的孩子:[yourValue] =“value” – Carsten

我通过将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 {}