【问题标题】:How to pass [(ng-model)] into @ViewChild in Angular4?如何在Angular4中将[(ng-model)]传递给@ViewChild?
【发布时间】:2017-10-09 07:42:16
【问题描述】:

我有一个组件,里面有 form 元素。此表单有一个input[type="number"],将用于调整iframe 元素。问题是,iframe 元素在@ViewChild 内部。如何将表单输入上的[(ng-model)] 传递给iframe 内部@ViewChild 上的[width]?代码如下所示:

@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>
      `
    })

 }

【问题讨论】:

    标签: javascript angular iframe


    【解决方案1】:

    最简单的方法是在您的子组件中创建一个 @Input() getter 和 setter:

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

    这将类似于 ngModel 父子关系

    【讨论】:

    • 你能快速演示一下吗?试过但无法传递值:(
    • 这是演示。您可以使用 html 表示法将值传递给您的孩子:[yourValue]="value"
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      相关资源
      最近更新 更多