angularjs-directiveangular-componentsangular-elements

How to pass Angular directive by reference?


In an existing component template I have this (simplified) element:

<input type="button" #refreshPrice />

This is picked up (I don't know the correct term) by this property so we can subscribe to it's click event and call a function when the input element is clicked.

I want to replace this input element with a component I've developed, which would make it look (simplified) like this:

<spinner-button #refreshPrice></spinner-button>

This child component has this as its (simplified) template:

<button>
    <mat-spinner></mat-spinner>
</button>

So now the button element, in the child component template, needs to have the #refreshPrice hash attribute (?) attached.

To do this, perhaps the spinner-button element should take the name of the hash attribute as an attribute value. Here is the complete spinner component class file:

import { Component, Input, OnInit } from "@angular/core";

@Component({
  selector: "spinner-button",
  templateUrl: "./spinner-button.component.html",
  styleUrls: ["./spinner-button.component.css"]
})
export class SpinnerButtonComponent implements OnInit {

  constructor() {}
  
  @Input() targetElement: string;

  ngOnInit() {
  }
}

In theory, the targetElement property can then be attached to the button element as a hash attribute - but how is this done?


Solution

  • the @Input() attribute here allows you to bind a value to a variable on your component, if you want to have the parent do something based on your components data, you might want to use @Output() and emit a custom event. If the requirement is just listen to a click event then adding a (click)=functionToBeCalled() should help your cause here.

    You can refer to the official docs as well: https://angular.io/guide/inputs-outputs