Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Using 'title' as @Input

Tags:

angular

Using the html attributes title as an @Input() leads to weird results.

running example: https://stackblitz.com/edit/angular-apd2mf

Hello.component.ts

@Component({
  selector: 'hello',
  template: `<h1>Hello {{title}}{{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  @Input() title: string;
}

app.component.ts

@Component({
  selector: 'my-app',
  template: `
    <hello name="{{ name }}" title="Mr. "></hello>
    <p>Start editing to see some magic happen :)</p>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
}

result enter image description here

The issue here is that I see the value of title input while hovering anywhere on the heading. I know I can avoid this by using it as

<hello name="{{ name }}" [title]="'Mr. '"></hello>

But is there a reason why angular is attaching the attribute even though I'm declaring it as an input?

like image 872
V.S Avatar asked Oct 27 '25 06:10

V.S


1 Answers

At least in Angular 13 you can clear the attribute simply by using HostBinding along with a getter:

@Input() title = '';

@HostBinding('attr.title') get getTitle(): null {
  return null;
}

No setter or elementRef references needed. Using null makes sure that the attribute name is removed, not just attribute value.

like image 51
certainlyakey Avatar answered Oct 28 '25 22:10

certainlyakey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!