2

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?

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • 1
    Is there a reason why you need a template ref to listen on the click event? Or can you also use the `(click)` event directly to call you function? – Norbert Bartko Jul 11 '22 at 11:44
  • 1
    The click event is the solution I have settled on. I posted this question because (naïve as I am) I /was/ under the impression that the hashtag attribute was being used for more than it was. I believed that it was allowing the component to reference and listen to events on the input element. – Matt W Jul 11 '22 at 12:31
  • 1
    I have voted to close it based on opinion. Because the opinion held when posted was wrong. – Matt W Jul 11 '22 at 12:35
  • Looks like xy problem. Could you explain better what are you trying? Also, remember to set # on html elements not selector – Vega Jul 14 '22 at 17:35

1 Answers1

1

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

gaurav
  • 256
  • 1
  • 4