2017-10-04 102 views
0

我正在構建一項新功能,使用戶可以使用輸入來調整iframe的大小。我有一個iframe,我想根據input type="number"來調整它的寬度。我想用指令的方式如何使用angular4上的輸入來調整iframe寬度?

@Component({ 
    selector: "demo-iframe", 
    template: ` 
     <form> 
      <input type="number" [customPx]="`test`">px 
      <button type="submit">Adjust width</button> 
     </form> 
    ` 
}) 

export class DemoIframeCmp { 
    @Input() public customPx: string; 
    public ngOnInit() { 
     if (this.customPx) { 
      console.log('YES', this.customPx); 
     } else { 
      console.log('NOPE', this.customPx); 
     } 
    } 
} 

這樣做的,但後來我發現我的輸入沒有customPx ATTR控制檯上的錯誤。我的問題是:

  • Directive是一個很好的方法嗎?
  • 對我的功能有更好的方法嗎?

回答

0

我認爲,在這種情況下使用指令並不是一個更好的解決方案,但您可以在理論上這樣做。當然,在控制檯中會出現這樣的錯誤,因爲本地輸入元素沒有'customPx'屬性。您必須使用'customPx'的選擇器編寫指令。

在我看來,有一個更好更簡單的方法:你可以使用angular的雙向綁定。 我爲此創建了一個Plunker。 有兩種變體可以獲得您需要的功能。

首先,正如我所說,是用雙向即時的iframe調整結合(如你型,換句話說):

模板:

<input [(ngModel)]="model.px">px 
<iframe [width]="model.px"></iframe> 

組件:

@Component(/*...*/) 
class Blabla { 
    model = { 
    px: 10 
    } 
} 

二是使用傳統的表單提交預防的默認事件行爲來調整你的iframe提交表單後,才:

模板:

<form #f="ngForm" (submit)="onSubmit($event)"> 
    <input [(ngModel)]="model.px">px 
</form> 
<iframe [width]="px"></iframe> 

組件:

@Component(/*...*/) 
class Blabla { 
    model = { 
    px: 10 
    } 

    onSubmit(event: Event) { 
    event.preventDefault() 
    this.px = this.model.px 
    } 
} 
+0

阿爽!謝謝! – ivanasetiawan

相關問題