2017-10-09 77 views
0

我有一個內部有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> 
     ` 
    }) 

} 

回答

0

最簡單的方法是在你的子組件來創建一個@input()getter和setter:

_yourValue; 
@Input() set yourValue(val) { 
    this._yourValue = val; 
} 
get yourValue() { 
    return this._yourValue; 
} 

這會像ngModel爲父母和孩子之間

+0

你可以給一個快速演示?嘗試它,但無法通過價值:( – ivanasetiawan

+0

這是演示。您可以使用html符號將值傳遞給您的孩子:[yourValue] =「value」 – Carsten

0

我通過將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 {} 
相關問題