相关疑难解决方法(0)

在Angular 2中测试ngOnChanges生命周期钩子

鉴于以下代码,我尝试测试ngOnChangesAngular2 的生命周期钩子:

import {
    it,
    inject,
    fdescribe,
    beforeEachProviders,
} from '@angular/core/testing';

import {TestComponentBuilder} from '@angular/compiler/testing';

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

@Component({
    selector: 'test',
    template: `<p>{{value}}</p>`,
})
export class TestComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: {}): any {
        // should be called
    }
}

fdescribe('TestComponent', () => {
    let tcb: TestComponentBuilder;

    beforeEachProviders(() => [
        TestComponentBuilder,
        TestComponent,
    ]);

    beforeEach(inject([TestComponentBuilder], _tcb => {
        tcb = _tcb;
    }));

    it('should call ngOnChanges', done => {
        tcb.createAsync(TestComponent).then(fixture => {
            let testComponent: …
Run Code Online (Sandbox Code Playgroud)

karma-jasmine angular2-testing angular2-components angular

25
推荐指数
3
解决办法
2万
查看次数

直接设置属性时ngOnChanges不触发

我使用了 ng-bootstrap 中的模态

在我的父组件中,我曾经modalService打开模态,然后使用将数据发送到模态componentInstance

在模态组件中,我用来ngOnChanges获取发送的数据。但未ngOnChanges触发。

堆栈闪电战

父组件

  public toAttach(): void {
    let modalRef = this.modalService.open(HelloComponent);
    modalRef.componentInstance.attachments = this.attachments;
  }
Run Code Online (Sandbox Code Playgroud)

模态成分

  ngOnChanges(changes: SimpleChanges) {
    console.log("start!");
    if (changes["attachments"] && changes["attachments"].currentValue) {
      console.log(changes["attachments"].currentValue);
    }
  }
Run Code Online (Sandbox Code Playgroud)

typescript angular

1
推荐指数
1
解决办法
1962
查看次数