在创建DOM之后向元素添加事件

时间:2016-02-04 19:38:34

标签: angular typescript

我试图找出在将元素添加到DOM后如何向元素添加事件。

现在,我有这样的事情:

import {Component} from 'angular2/core';

@Component({
    selector   : 'sub-child',
    template   : '<form [innerHTML]="html"></form>'
})

export class SubChildClass
{
    private html:string;
    private buttonText:string;

    constructor()
    {
        this.buttonText = 'A new button';
        this.create();
    }

    private create()
    {
        this.html = "<button (click)='new()'>" + this.buttonText + "</button>"
    }

    private new()
    {
        this.buttonText = "Text Changed";
    }
}

不起作用的部分是:

this.html = "<button (click)='new()'>" + this.buttonText + "</button>"

Angular 2目前还不知道如何处理(click)='new()'。我不确定什么是正确的方法。

我期望能够在稍后的某些相应事件中将DOM添加到DOM中。

我还没有使用Angular 1.但听起来这曾经相当于$compile in Angular 1。其他一些帖子建议使用Dynamic Content Loader这样的东西。但这似乎不是这个用例的正确答案。所以任何帮助或指导都表示赞赏。谢谢,

2 个答案:

答案 0 :(得分:9)

更新了建议

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

@Component({
  selector: 'special-button-component',
  template: '<button type="button" (click)="changeText()">{{buttonText}}</button>'
})
export class SpecialButtonComponent{
  public buttonText: string = 'A New Button';
  public changeText(): void{
    this.buttonText = 'Text Changed';
  }
}

@Component({
  selector   : 'sub-child',
  template   : '<form><special-button-component></special-button-component></form>'
})
export class SubChildClass{}

原始答案 (由于从Angular 2中删除了BrowserDomAdapter,因此无效)

如果您确实想要绑定到已经注入的非模板DOM元素,那么您可以使用Angular2的一些相当未记录的功能来设置事件监听器的良好方式

import {Component, ElementRef} from 'angular2/core';
import {BrowserDomAdapter} from 'angular2/platform/browser';

@Component({
  selector   : 'sub-child',
  template   : '<form [innerHTML]="html"></form>'
})
export class SubChildClass
{
  private html:string;
  private buttonText:string;

  constructor(private elementRef: ElementRef, private domAdapter: BrowserDomAdapter)
  {
    this.buttonText = 'A new button';
    this.create();
  }

  private create()
  {
    let button = this.domAdapter.createElement('button');
    button.innerHtml = this.buttonText;
    this.domAdapter.on(button, 'click', this.new.bind(this));
    this.domAdapter.appendChild(this.elementRef.nativeElement, button);
  }

  private new()
  {
    let button = this.domAdapter.querySelector(this.elementRef.nativeElement, 'button');
    button.innerHTML = "Text Changed";
  }
}

但重点是什么......如果我们只是降到这个水平,为什么首先使用角度。我也在生产中的企业应用程序中使用Angular2。我对此功能的选择是将button本身创建为Component,然后使用DynamicComponentLoader将元素注入。

答案 1 :(得分:1)

我使用ngFor来重复DOM。按下单击按钮时,将项目添加到阵列。例: +组件:

        IWaveProvider provider = null;
        var stream = new MemoryStream();
        using (var synth = new SpeechSynthesizer())
        {

            synth.SetOutputToAudioStream(stream,
                new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
            synth.Speak("This is sample text-to-speech output.");

            stream.Seek(0, SeekOrigin.Begin);
            provider = new RawSourceWaveStream(stream, new WaveFormat(44100, 16, 1));

        }
        var waveOut = new WaveOut();
        waveOut.Init(provider);
        waveOut.Play();
  • HTML:

export class AbcComponent {
  billingInforArr: RegisterBillingInfoModel[] = [];

  months: any[] = [];
  years: any[] = [];

  constructor(private fb: FormBuilder, private router: Router) {
    for (let i = 1; i <= 12; i++) {
      this.months.push({ value: i, text: i });
    }

    let today = new Date();
    let year = today.getFullYear();
    for (let i = 1; i <= 10; i++) {
      this.years.push({ value: year + i, text: year + i });
    }

    if (localStorage.getItem('listCard') != null) {
      this.billingInforArr = JSON.parse(localStorage.getItem('listCard'));
    }
  }
  addCard(value: any) {
    this.billingInforArr.push({ Id: Date.now().toString(), NameOnCard: value.name, CardNumber: value.cardNumber, ExpMonth: value.expMonth, ExpYear: value.expYear, Expire: `${value.expMonth}/${value.expYear}` });
    localStorage.setItem('listCard', JSON.stringify(this.billingInforArr));
  }
  removeCard(value: any) {
    console.log(value);
    console.log(this.billingInforArr);

  }
}