I'm a newcomer to Angular2, I'm used to the Angular 1 digest cycle, meaning if I update the scope of a view I can manually trigger a digest by calling $scope.$digest()
. However, I'm not sure how to do this in Angular2, esp given that the new framework doesn't have the implicit data binding that the old version had.
Here's my problem. I have a route that loads a component when a url with a parameter is hit:
// Router export const AppRoutes : RouterConfig = [ { path: 'my/:arg/view', component: MyComponent } ]
Then I have this component:
// Component export class MyComponent { constructor(private route : ActivatedRoute, private r : Router) { let id = parseInt(this.route.params['value'].id); console.log(id); // do stuff with id } reloadWithNewId(id:number) { this.r.navigateByUrl('my/' + id + '/view'); } }
Lets say I navigate to url /my/1/view
. It will call the constructor and the number 1
is logged. However, if I call reloadWithNewId
with a new id, reloadWithNewIf(2)
, the constructor is not called again. How do I manually reload the component?
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
To force the child component to re-render — and make a new API call — we'll need to pass a prop that will change if the user's color preference has changed. This is a simple switch we can flip.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically. However, there may be cases where the render() method depends on some other data.
In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.
There shouldn't be a need to reload the component. Just update the model and the view updates itself:
export class MyComponent { constructor(private route : ActivatedRoute, private r : Router) {} reloadWithNewId(id:number) { this.r.navigateByUrl('my/' + id + '/view'); } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.paramsChanged(params['id']); }); } paramsChanged(id) { console.log(id); // do stuff with id } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With