1. 程式人生 > >angular學習總結十——動態建立元件並實現互動一

angular學習總結十——動態建立元件並實現互動一

ps:看了好多篇動態元件的部落格,坑啊,只是放進去一個靜態元件,並未加上Input,Output

appModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { DynamicComponent } from './dynamic/dynamic.component'
; @NgModule({ declarations: [ AppComponent, DynamicComponent ], entryComponents: [DynamicComponent], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

首先動態元件1的實現方式必須在entryComponents中宣告

app.component.ts

import
{ Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core'; import { DynamicComponent } from './dynamic/dynamic.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'
; username = 'zengwe'; @ViewChild('content', { read: ViewContainerRef }) content: ViewContainerRef; constructor(private componentFactory: ComponentFactoryResolver) { } add() { const component = this.componentFactory.resolveComponentFactory(DynamicComponent); component.inputs.push({propName: 'dd', templateName: 'ss'}); const com = this.content.createComponent(component); console.log(com.instance); com.instance.dd = 'dd傳的值'; com.instance.out.subscribe((res) => { console.log(res); }); } remove() { this.content.clear(); } }

1.com.instance就是向元件中加入資料和訂閱Output的事件
this.content.createComponent(component)中的引數中可加入第二個引數id:number
這樣可以this.content.remove(id)刪除指定的元件

app.component.html

<div>
  <h1>dynamic</h1>
  <div>
    <h2>dynamic container</h2>
    <div #content></div>
  </div>
  <button (click)="add()">add</button>
  <button (click)="remove()">remove</button>
</div>

dynamic.componet.ts

import { Component, OnInit, Input, AfterViewInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-dynamic',
  templateUrl: './dynamic.component.html',
  styleUrls: ['./dynamic.component.css']
})
export class DynamicComponent implements OnInit, AfterViewInit {
  @Input('dd') dd: any;
  @Input('ss') ss: any;
  @Output('out') out = new EventEmitter();
  constructor() { }

  ngOnInit() {
  }
  ngAfterViewInit() {
    console.log(this.dd);
    console.log(this.ss);
    console.log(this);
  }
  outEvent() {
    this.out.emit('outValue');
  }
}

dynamic.component.html

<div class="">
  <span>dynamic componet</span>
  <div>{{dd}}</div>
  <div>{{ss}}</div>
  <button (click)="outEvent($evnet)">click out value</button>
</div>