I'm writing an Angular component that has a property Mode(): string
. I would like to be able to set this property programmatically not in response to any event. The problem is that in the absence of a browser event, a template binding {{Mode}}
doesn't update. Is there a way to trigger this change detection manually?
相关问题
- Angular RxJS mergeMap types
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- How to update placeholder text in ng2-smart-table?
- How to instantiate Http service in main.ts manuall
- Angular: ngc or tsc?
相关文章
- angular脚手架在ie9+下兼容问题
- angular 前端项目 build 报错 "Cannot find module 'le
- Angular Material Stepper causes mat-formfield to v
- After upgrade to Angular 9 cannot find variable in
- is there any difference between import { Observabl
- Suppress “Circular dependency detected” suppress w
- How can you get current positional information abo
- Angular material table not showing data
I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:
Import
NgZone
:Add it to your class constructor
Run code with
zone.run
:In Angular 2+, try the @Input decorator
It allows for some nice property binding between parent and child components.
First create a global variable in the parent to hold the object/property that will be passed to the child.
Next create a global variable in the child to hold the object/property passed from the parent.
Then in the parent html, where the child template is used, add square brackets notation with the name of the child variable, then set it equal to the name of the parent variable. Example:
Finally, where the child property is defined in the child component, add the Input decorator:
When your parent variable is updated, it should pass the updates to the child component, which will update its html.
Also, to trigger a function in the child component, take a look at ngOnChanges.
I was able to update it with markForCheck()
Import ChangeDetectorRef
Inject and instantiate it
Finally mark change detection to take place
Here's an example where markForCheck() works and detectChanges() don't.
https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview
(Press STOP/RUN to run it again)
Try one of these:
ApplicationRef.tick()
- similar to AngularJS's$rootScope.$digest()
-- i.e., check the full component treeNgZone.run(callback)
- similar to$rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.ChangeDetectorRef.detectChanges()
- similar to$scope.$digest()
-- i.e., check only this component and its childrenYou can inject
ApplicationRef
,NgZone
, orChangeDetectorRef
into your component.