0

We got used to make variables protected which are only used in a component and its subclasses but not in the template.

That's especially an advantage if you have like 10 many variables in your class and with protected private and public it's very easy to know which variables are used in the template.

@Input() public disablePlus: boolean = false;
@Input() public disableMinus: boolean = false;

@Input() protected jumpSize: number = 1000;

now I'm about to create some unit-test for this component. But i cannot activly change those values inside my it method:

it('should change jumpSize to 5000', () => {
    component.jumpSize= 5000; 
    // ts2445: Property `jumpSize` is protected and only accessible within class and its subclasses
    ...
});

it('plus should be disabled', () => {
    component.disablePlus= true; // no error
    ...
});

Is there a way to leave jumpSize protected or do we have to change it to public?

Or do you event think that our approach with protected @Input fields is anyway stupid and not very useful?

I'm thankful for any advice.

1 Answer 1

1

I've never seen any example of that (using protected on an input).

In fact, they should be public because as the name speaks by itself, an input should be updated from outside the class. Do you use AOT on your app? I'm even surprise if that compile actually.

And from Angular point of you, it'll be the same problem that you have in your test to update the property. If you're in dev mode, then it uses JIT (just in time compilation) and you don't get that kind of checks from the template. That's why it might be working.

Conclusion: Just put all your inputs public.

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

2 Comments

But do you compile your prod bundle with AOT?
Also, it's just a typescript check and once typescript is compiled, there's absolutely no effect at runtime. So you're either not compiling with AOT or for some reason TS can't catch that probably because it comes from a template call (which should be transpiled into TS code with AOT but hey... no idea why it doesn't catch it :D)

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.