0

I am trying to pass some value in my custom Directive but when trying to do so, I am getting error

home.component.ts

<div *myNgIf myNgIfSomething="true" class="col-sm-6">
    <div class="form-group">
        <label for="lname">LastName</label>
        <input class="form-control" type="text" name="lname">
    </div>
</div>

Directive

 @Directive({
    selector: '[myNgIf]'
})
export class myNgIfDirective implements AfterViewInit {

    @Input() myNgIfSomething: boolean = false;

    constructor(private container: ViewContainerRef, private template: TemplateRef<any>) { }

    ngAfterViewInit(): void {
        if(this.myNgIfSomething){
            this.container.createEmbeddedView(this.template)
        }else{
            this.container.clear()
        }
    }

}

error

enter image description here

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85
  • I tried, but it is still giving me error, I am able to run the code successfully with this code,
    but i want to implement the directive syntetic sugar
    – Lijin Durairaj Jun 30 '22 at 13:33
  • @mbojko, it says, it should be prefixed with the directive name followed by the input name captilized, which is exactly i am using but i am getting error – Lijin Durairaj Jun 30 '22 at 13:38
  • it's not how you consume a custom structural directive in a template. Just like that's not the syntax for the standard structural directives you get OOTB. You write `*ngIf="someCondition; else refToAnotherTemplate"`. – mbojko Jun 30 '22 at 13:44
  • @mbojko, could you guide me on what is the proper way to get an input from the directive, I couldnt find that in any blog – Lijin Durairaj Jun 30 '22 at 13:52
  • The first answer in the thread I linked above provides all parts: the logic of the directive, and how do you actually use it in a template. – mbojko Jun 30 '22 at 13:54
  • as suggested by @mbojko, this post answers the question https://stackoverflow.com/questions/41789702/how-to-use-angular-structural-directive-with-multiple-inputs – Lijin Durairaj Jun 30 '22 at 15:07

1 Answers1

-2

You forgot the brackets while setting your input in the template. It should be:

<div *myNgIf [myNgIfSomething]="true" class="col-sm-6">

When setting an HTML node property inside the template, you use the brackets, then you have a javascript expression between the quotes. In your case, you want the JS value "true" for this "property", so use the brackets. Otherwise, Angular will interpret this property as a string, just like a normal property of an HTML node.

  • That's for attribute directives (used without asterisk). For structural directives, you use inputs differently: `*myNgIf="someValue; something anotherValue`. – mbojko Jun 30 '22 at 14:36
  • Well, this is definitely what his error is saying. He sets the selector has an attribute directive, has an myNgIfSomething Input and calls it without brackets. So using brackets and removing the asterisk would work. – thomasgainant Jul 01 '22 at 15:22