0

I want to pass a static value from html to component but it's just not working, I have been stuck all day long... could you give me some glue? Thanks

component:

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

@Component({
  selector: 'rio-hello',
  template: `<p>Hello, {{name}}!</p>
    <button (click)="greet()">Show Greet</button>
  `,
})
export class HelloComponent {
  @Input()
  name: string;

  greet(){
    console.log(`Hello,${name}`);
  }
}

entry html index.html

<rio-hello name="World"></rio-hello>

What I'm expecting is it can print Hello, World on the page and name property can be set to World in component, how to make it?

user1231111
  • 397
  • 2
  • 6
  • 16

1 Answers1

1

You need to add this to refer name since it is part of your instance of HelloComponent:

greet() {
  console.log(`Hello, ${this.name}`);
}

Your template looks fine.

Edit: Since you are using @Input in a bootstrapped component, it seems not possible to do so:

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • it's not really working even adding keyword this. Console says Hello,undefined , and page displays Hello,!, World just not got by component. – user1231111 Jul 06 '20 at 01:52
  • Can you add `` to your app.component.html instead of index.html (where `` should be in index.html)? – pzaenger Jul 06 '20 at 01:53
  • Yes, that should be working if I make the app component as bootstrap component and use rio-hello in app.component.html, but it's not my exact expectation , I hoped to give user a chance to directly set the name value on first place, index.html instead of parent component. I created a live angular project at https://stackblitz.com/edit/angular-ivy-gmzdeh where everyone can edit and run it online, maybe you could take a look. Thanks for your answer – user1231111 Jul 06 '20 at 03:04
  • Is it possible to get the property of a bootsrapped component which seems very useful? Suppose that app component need to parse a file whose name and path is configured on a property. Without the ability to get the path directly we are not able to parse it. Seems likely @input is only working for data passing between parent and children components – user1231111 Jul 22 '20 at 00:31