1

I'm reading angular docs.It just spawned a doubt in my mind about the following sentence REF

"evaluation of a template expression should have no visible side effects..."

If i understood correctly, it's because a "single detection cycle" executes the "templete expression": if that template expressions alters an info on which the rendered view depends, it won't show the change within that detection cycle...

My doubt is: for the same reason, is it safe to say that

a component with input a setter must not allow the setter to have visible side effects

Example
Can the following result in: the "list" does not render correctly when passing an input to the component

interface MyType{
    description: string
}

@Component({
    selector: 'my-cmp',
    template: `
        <div *ngFor="let item of _list">{{item.description}}</div>
    `
}),
export class MyComponentList{

    _list: MyType[];

    @Input() set list( items: MyType[] ){
        if(isListValid){
            this._list = items;
        }
        this._list = [];
    }

    isListValid( aList: MyType[] ): boolean{
        // logic
    }

}

1 Answer 1

1

"evaluation of a template expression should have no visible side effects..."

It means, that is you use something in the template, the fact that you used it, should not have any side effects like perfomring an request, changing data model, modyfying dom etc, changing some properties.

The last case can be annoying and hard to debug as you can get ValueChangedAfterCheckedException errors when - for example - you are incrementing some counter everytime you use some sort of getter method, that is also used in the template.

Now as for your statement:

a component with input a setter must not allow the setter to have visible side effects

that rly depends on the case - in general there will be no problem with that, as @Inputs are evaluated and bound before target component is initialized/has detection run on it, thus it can alter compontents state.

So in your case, everything will be fine, as setter will run before change detecion/rerender of component happens. Otherwise - it falls back to "no side effects" general rule.

If you take closer look, you will see that onChanges (thats called when @input/@output is involved) is the FIRST LIFECYCLE CALBACK of the angular component. (Its even before onInit callback). So that is the place to do modifications - and setters are invoked even before that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.