标签: angular2-changedetection

behaviourSubject in angular2,它是如何工作的以及如何使用它

我正在尝试构建一个共享服务,如下所示

import {Injectable,EventEmitter}     from 'angular2/core';
import {Subject} from 'rxjs/Subject';
import {BehaviorSubject} from 'rxjs/subject/BehaviorSubject';
@Injectable()
export class SearchService {

    public country = new Subject<SharedService>();
    public space: Subject<SharedService> = new BehaviorSubject<SharedService>(null);
    searchTextStream$ = this.country.asObservable();

    broadcastTextChange(text: SharedService) {
        this.space.next(text);
        this.country.next(text);
    }
}
export class SharedService {
    country: string;
    state: string;
    city: string;  
    street: string;
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现BehaviourSubject基本上我在这里尝试的只是一团糟我猜我在使用子组件调用这个值

console.log('behiob' + shared.space.single());
Run Code Online (Sandbox Code Playgroud)

这是一个错误,因为.single()/ last()等等什么是可用的不是一个函数所以有人可以告诉我它是如何工作的以及如何实现它,因为我搜索的例子但没有一个对我有意义.

rxjs angular2-changedetection angular

13
推荐指数
1
解决办法
2万
查看次数

如何禁用第三方库的angular2更改检测

我有谷歌地图,每秒触发100次以上的变化检测.如何禁用此更改检测.

点击此处查看地图预览

使用鼠标悬停事件时会更糟.

ngDoCheck() {
  console.log('do check', this.i++);
}
Run Code Online (Sandbox Code Playgroud)

angular2-changedetection angular

13
推荐指数
2
解决办法
8258
查看次数

阻止本机浏览器事件(如滚动)触发更改检测

我正在绑定一个滚动事件来捕获滚动并用它做一些事情,我创建了一个像bellow一样的指令:

所以我有简单的指令,除了:

      constructor ( private el : ElementRef ,
                        private renderer : Renderer ) {
              this.domAdapter = new browser.BrowserDomAdapter();
              this.ruler      = new Ruler( this.domAdapter );
      }
      ngAfterViewInit () : any {
              this.renderer.listenGlobal( 'window' , 'scroll' , ()=> {
                  console.log( 'scrolling' );
              } );
              return undefined;
      }
Run Code Online (Sandbox Code Playgroud)

这工作正常,期望我可以看到它在我的所有应用程序中触发滚动更改检测.

这是我的一个组件内部:

     private  aFunction () {
             console.log( 'change detected !!!' );
     }
Run Code Online (Sandbox Code Playgroud)

aFunction在某个组件的某个地方有一个模板:

       <div>{{ aFunction() }}</div>
Run Code Online (Sandbox Code Playgroud)

之前,aFunction只有当我更新了一些输入或点击了一个按钮时才会被解雇,但现在,它正在滚动时进行更改检测!因此,我的滚动体验是滞后的!

这是Angular2的正常行为,所有事件都应该触发更改检测,但我想从此规则中排除我的滚动事件.

简而言之,如何在Angular2中定义一个事件,并将其转换为触发变更检测并使其成为手动的能力.

我在找 :

    this.renderer.listenGlobalButDontFireTheChangeDetection
Run Code Online (Sandbox Code Playgroud)

angular2-changedetection angular

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

检测由父角度2触发的子组件变量的变化

我有2个文件.app.ts和Child.ts

我正在从app向子节点发送变量,我想检测变量中的任何变化并相应地显示数据.我无法检测到变量的变化.

任何帮助?我附上了Plunker Link,我还在评论中解释了我想在Child.ts文件中做什么

App.ts文件

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChildCom} from './child.ts'

@Component({
    selector: 'my-app',
    template: `
    <div>
        <h2>Hello</h2>
        <child-com newdata={{data}}></child-com>
    </div>
    `,
})
export class App {
    data: any = [];

      constructor(){
          this.data = [{"name":"control","status":"false"}];
    }
}

@NgModule({
    imports: [ BrowserModule ],
    declarations: [ App, ChildCom ],
    bootstrap: [ App ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

Child.ts文件

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

@Component({
  selector: 'child-com',
  template: `
    <div>
      <p>Controls: …
Run Code Online (Sandbox Code Playgroud)

eventemitter angular2-changedetection angular

12
推荐指数
1
解决办法
2万
查看次数

从电子容器IPC通道接收数据时,变更检测会间歇性地工作

我有一个正在侦听来自IPC渲染器通道的​​传入数据的应用程序。这是我的设置:

将数据发送到角度应用程序(mainWindow)的容器:

mainWindow.loadURL('http://www.myangularapp.com') //where the angular app lives (example url).
mainWindow.webContents.on('did-finish-load', () => {
      const data = { name: "John Doe", address: "123 Main St", city: "NY"}
      mainWindow.webContents.send('data-from-container', data)
        }
    })
Run Code Online (Sandbox Code Playgroud)

角度应用:

constructor(
    private store: Store<fromStore.AppState>,
    private cd: ChangeDetectorRef,
    private zone: NgZone,
  ) {}

  ngOnInit() {
this.isLoading = true;
    if (this.electronService.ipcRenderer) {
      this.electronService.ipcRenderer.on('data-from-container', (event, data) => {
        this.zone.run(() => {
          if(data){
            setTimeout(() => {
              console.log(data) // verified data is always received
              this.formData = data; // property that form uses to …
Run Code Online (Sandbox Code Playgroud)

javascript ipc electron angular2-changedetection angular

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

即使列表引用发生变化,如何重用ngFor的元素?

我有一个Angular 2组件,用于*ngFor渲染嵌套的数字数组.

@Component({
  selector: 'app',
  template: `
    <div *ngFor="let row in data">
      <div *ngFor="let curve in row">
        <chart [data]="curve">
      </div>
    </div>
  `,
  directives: [Chart],
})
export default class App {
  data: number[][][];
}
Run Code Online (Sandbox Code Playgroud)

当我改变时data,<chart>即使新数组具有相同的尺寸,Angular 也会替换元素.我只想更新图表的属性但保留元素(以便我可以设置数据变化的动画).

可以理解,Angular会替换元素,因为新数组是一个新的对象引用.但我怎么能绕过这个呢?

angular2-template ngfor angular2-changedetection angular

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

Angular 2:ChangeDetection和mousemove事件

我有一个Angular 2组件,有很多孩子.由于性能问题,我想检查ChangeDetection检查我的子组件的频率.所以我记录了我的一个子组件的ngAfterViewChecked -callback.

我意识到我的父组件有一个mousemove()- callback,所以每当我将鼠标移到父母上时,我的孩子的ngAfterViewChecked就会被调用.但是我没有更新mousemove()- callback中的任何组件变量.为什么ChangeDetection会为孩子们运行,我该如何阻止它?

希望你们明白这个问题(如果没有请注释,这样我就可以清楚了解问题).谢谢你的帮助!

dom-events angular2-changedetection angular

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

从子1更新父组件中的值会导致Angular中的ExpressionChangedAfterItHasBeenCheckedError

我有两个组件:ParentComponent > ChildComponent和一个服务,例如TitleService.

ParentComponent 看起来像这样:

export class ParentComponent implements OnInit, OnDestroy {

  title: string;


  private titleSubscription: Subscription;


  constructor (private titleService: TitleService) {
  }


  ngOnInit (): void {

    // Watching for title change.
    this.titleSubscription = this.titleService.onTitleChange()
      .subscribe(title => this.title = title)
    ;

  }

  ngOnDestroy (): void {
    if (this.titleSubscription) {
      this.titleSubscription.unsubscribe();
    }
  }    

}
Run Code Online (Sandbox Code Playgroud)

ChildComponent 看起来像这样:

export class ChildComponent implements OnInit {

  constructor (
    private route: ActivatedRoute,
    private titleService: TitleService
  ) {
  }


  ngOnInit (): void { …
Run Code Online (Sandbox Code Playgroud)

angular2-changedetection angular

9
推荐指数
2
解决办法
6061
查看次数

使用反应式表单和 ChangeDetectionStrategy.OnPush 显示验证消息

我正在尝试将应用程序迁移到使用ChangeDetectionStrategy.OnPush. 然而,我在尝试使用一些反应形式时遇到了一些阻碍。

我有一个可重用的控件,可以根据某些状态标志(例如*ngIf="control.touched && control.invalid")显示验证消息。我遇到的问题是,无法检测touched标志何时更改,因此无法使用ChangeDetectorRef.

可以通过侦听事件来引用输入元素本身来完成click但这并不能说明何时markAsTouched()使用,并且传递对元素的引用并不总是可行的,而且总是不优雅。

有没有一种方法可以使用OnPush并仍然响应表单控件状态(例如touched),或者只是通常很痛苦?

angular2-changedetection angular angular-reactive-forms angular-changedetection

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

为什么我需要使用默认的更改检测策略调用detectChanges()?

我正在开发一个Angular 4应用程序,但我遇到了一个问题,因为我不得不this.changeDetectorRef.detectChanges();在模型更改时调用更新视图.例如,我有这个用于分页的代码:

changePage(pageNumber) {
  this.currentPage = pageNumber;
  // why do I need to do this?
  this.changeDetectorRef.detectChanges();
}
Run Code Online (Sandbox Code Playgroud)

我已经明确地在组件上设置了更改检测策略,ChangeDetectionStrategy.Default但这没有任何效果.在订阅一个observable时也会发生这种情况:

showResults(preference) {
  this.apiService.get('dining_autocomplete/', `?search=${preference}`)
    .subscribe((results) => {
      this.searchResults = results;
      // why do I need to do this?
      this.changeDetectorRef.detectChanges();
  });
}
Run Code Online (Sandbox Code Playgroud)

如果我console.log() this.searchResults在TypeScript中,我得到了预期的结果,但是如果我{{ searchResults }}在HTML中使用它,它就不会更新,直到其他事件发生,大概是当它经历另一个摘要周期时.

会发生什么事?

==编辑=============================================== ============

我的组件的代码如下所示:

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

import * as _ from 'lodash';

@Component({
  selector: 'dining-search-results',
  templateUrl: './dining-search-results.template.html',
  styleUrls: ['./dining-search-results.style.scss'],

})
export class DiningSearchResultsComponent { …
Run Code Online (Sandbox Code Playgroud)

typescript angular2-changedetection angular

8
推荐指数
1
解决办法
2万
查看次数