如何在Angular4中将[(ng-model)]传递给@ViewChild?

时间:2017-10-09 07:42:17

标签: javascript angular iframe

我有一个内部有form元素的组件。此表单包含input[type="number"],用于调整iframe元素。问题是,iframe元素位于@ViewChild内。如何将表单输入上的[(ng-model)]传递给[width] iframe内的@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>
      `
    })

 }

2 个答案:

答案 0 :(得分:0)

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

private final FilteredList<ReadOnlyPerson> filteredPersons;

@Override
public void sortFilteredPersonList() {

    Comparator<ReadOnlyPerson> sortByName = new Comparator<ReadOnlyPerson>() 
{
        @Override
        public int compare(ReadOnlyPerson o1, ReadOnlyPerson o2) {
            return o1.getName().fullName.compareTo(o2.getName().fullName);
        }
    };

   filteredPersons.sort(sortByName);
}

这将像父子一样的ngModel

答案 1 :(得分:0)

我通过将form放在子组件中来解决它。此外,我使用Angular的数据绑定行为,而不是使用@Directive。这样的事情,但在@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 {}