【问题标题】:How to adjust iframe width using an input on angular4?如何使用 angular4 上的输入调整 iframe 宽度?
【发布时间】:2017-10-04 13:42:27
【问题描述】:

我正在构建一个新功能,使用户能够使用输入来调整 iframe 的大小。我有一个iframe,我想根据input type="number" 调整它的宽度。我正在考虑用指令方法来做这件事

@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 是个好方法吗?
  • 我的功能有更好的方法吗?

【问题讨论】:

    标签: javascript angular iframe


    【解决方案1】:

    我认为,在这种情况下,使用 Directive 并不是一个更好的解决方案,但理论上你可以这样做。当然,您会在控制台中收到此类错误,因为本机输入元素没有“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
       }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2011-03-24
      • 2013-05-03
      • 2018-03-10
      • 2019-04-01
      相关资源
      最近更新 更多