Search code examples
angularangular-materialsingle-page-applicationstrict

MatMenuTrigger while using strict settings


Edit: We want to use strict alongside more compiler flags

Original:
For some background info, we are trying to cleanup our huge internal angular system, some of the choices we made were to setup compiler options to force stricter coding

    ...
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "strict": true,
    "allowUnreachableCode": false,
    "noImplicitAny": true,
    "noImplicitReturns": true

For example these settings, most of our coding standards already make sure most of these are easy enough to fix as we already type variables and have our config setup to format docs on save (prettier config as well as removing unused imports etc).

I know this may seem tedious however it basically means we can give our coding standards to new employees, ask them to setup the editor(s) with our rules and they should be able to start doing basic tasks without needing to ask lots of questions.

Now for the real problem:

@ViewChild(MatMenuTrigger) contextMenu: MatMenuTrigger;

A MatMenuTrigger requires many inputs in its constructors, has anyone dealt with creating these with strict on ? How would you go about this ? Is there a clean easy way to do this or will one have to create all the constructor params (7 - 9) of them (To be fair I think it needs 2 and you can pass nothing to the rest).


Solution

  • When using ViewChild, Angular will automatically set and update the element. You should not construct the element by yourself, it's the wrong approach. You don't want to create a new component, you want to get the instance of the component that is used in the template. To achieve this, you can fix the TypeScript errors by marking the attribute as optional. To do this, suffix the attribute name with ?:

    @ViewChild(MatMenuTrigger) contextMenu?: MatMenuTrigger;
    

    You might need some extra checks in your code to handle the possibility of the attribute being undefined, but this reflects reality the best, as a ViewChild is only available after view init.

    Alternatively you can use the non-null assertion !. With this approach you don't need to add extra checks, but the chance to produce bugs is higher, for example when you try to access the ViewChild on init.