Angular 2动态组件范围

时间:2017-03-21 13:41:27

标签: javascript angular

我一直在学习Angular 2及其新功能,我在动态添加组件时遇到了麻烦。

所以我有一个 dashboard.component.ts

import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver, ViewChild }    from '@angular/core';

import { InputTextComponent } from '../input-text/input-text.component'

@Component({
    templateUrl: 'dashboard.component.html',
    providers: [InputTextComponent],
    styleUrls: ['dashboard.component.css']
})

export class DashboardComponent implements OnInit {

    constructor( private componentFactoryResolver: ComponentFactoryResolver,
                 private viewContainerRef: ViewContainerRef,
                 private inputTextComponent: InputTextComponent
               ) { }

    @ViewChild(InputTextComponent) textComponent: InputTextComponent

    attachIntup(){
        const factory = this.componentFactoryResolver.resolveComponentFactory(InputTextComponent);
        const ref = this.viewContainerRef.createComponent(factory);
        ref.changeDetectorRef.detectChanges();
    }

    alertPop(){
        alert(this.textComponent.passingStr);
    }

    ngOnInit() {
    }
}

它有一个HTML代码 dashboard.component.html

<button (click)="attachIntup()">Inject Input</button>
<button (click)="alertPop()">Pop String</button>

和我的 inputTextComponent 如下

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-input-text',
  templateUrl: './input-text.component.html',
  styleUrls: ['./input-text.component.css']
})
export class InputTextComponent implements AfterViewInit {

  public inputType = '';
  public passingStr = '';

  constructor() { }


  popupAlert(){
    alert(this.passingStr);
  }

  ngAfterViewInit() {

    this.inputType = 'text'
  }

}

使用html:

<div [ngSwitch]="inputType" class="container">
    <div class="row" *ngSwitchCase="'textarea'">
        <div class="col-md-4">
            <label>I am a textarea: </label>
        </div>
        <div class="col-md-8">
            <textarea style="resize: both" class="form-control"></textarea>
        </div>
    </div>
    <div class="row" *ngSwitchCase="'text'">
        <div class="col-md-4">
            <button (click)="popupAlert()"></button>
            <label>I am an input text: </label>
        </div>
        <div class="col-md-8">
            <input type="text" class="form-control" placeholder="Testing text" [(ngModel)]="passingStr">
        </div>
    </div>
</div>

我要做的是从仪表板组件内的inputTextComponent获取范围。我已经读过ViewChild允许您访问组件内的变量,但在我的情况下我无法这样做。

有没有人知道如何在注入后访问InputTextComponent中的变量;为了在仪表板的警报中显示通过输入传递的任何信息。

提前致谢

0 个答案:

没有答案