Mat*_*zzo 3 angular angular6 angular-elements
所以我有这个简单的组件:
import {
Component,
ViewEncapsulation,
OnInit,
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'custom-element',
template: '<div>{{ chuckText$ | async }}</div>',
styleUrls: ['./button.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class ButtonComponent implements OnInit {
public chuckText$ = new BehaviorSubject<string>('');
public constructor(
private http: HttpClient
) {
this.chuckText$.next('Default Text');
}
ngOnInit() {
// nothing too fancy, just for testing purpose
this.http.get('https://api.chucknorris.io/jokes/random')
.subscribe((data: any) => {
console.log(data.value);
this.chuckText$.next(data.value);
});
}
}
Run Code Online (Sandbox Code Playgroud)
构建我的组件并将其添加到一个简单的angularJS应用程序后,(我需要将一个自定义元素添加到旧应用程序)我在控制台中使用默认文本和http.get结果获取我的元素,但我的组件尚未被更新,如图所示.
我显然遗漏了一些对我来说不太明显的事情.有关为什么内容不更新的任何想法?作为提醒,这个功能已经发布,但处于实验状态,也许就是这样.
作为参考,这是我的app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { HttpClientModule } from '@angular/common/http';
import { ButtonComponent } from './button/button.component';
@NgModule({
declarations: [ButtonComponent],
imports: [BrowserModule, HttpClientModule],
entryComponents: [ButtonComponent],
})
export class AppModule {
constructor(private injector: Injector) {
const customElement = createCustomElement(ButtonComponent, { injector });
customElements.define('custom-button', customElement);
}
ngDoBootstrap() { }
}
Run Code Online (Sandbox Code Playgroud)
我的一些自定义元素也遇到了同样的问题.某些情况下,change detection客户元素中的行为与常规角度应用程序中的行为不同,因此不会更新视图.
解决方案1
如果要更新组件的状态,请changeDetection手动调用.
ChangeDetectorRef在组件的构造函数中注入并调用markForCheck()或detectChanges()每次要更新视图时.
注意detectChanges().它将启动changeDetection进程,并且当您没有明智地使用它时可能会出现性能问题.
解决方案2
注入NgZone组件并调用NgZone.run().
例如:
this.ngZone.run(() => this.chuckText$.next(data.value))
| 归档时间: |
|
| 查看次数: |
718 次 |
| 最近记录: |