5

I am trying out writing web components in Angular and I cannot seem to figure out how to pass data into the component.

<my-component someId="1234"></my-component>

I was hoping to find some way to implement this and get the someId in my angular component. Is it possible to implement this or should I be trying to use slots? Just to be clear I'm asking how to make web components using angular not normal angular components.

Vinaayakh
  • 512
  • 1
  • 6
  • 17

4 Answers4

0

You should make use of Angular's data binding

<my-component [id]="1234"></my-component>

And on your child component, make use of the @Input decorators

export class MyComponent {
  @Input('id') id: string;
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • If the web component is injected in React, the square bracket in the `` will throw error in the react application. Do you know how to solve that ? – I'm nidhin Jan 05 '23 at 07:12
0

You need to use @Input() variable declared in your shared component.

export class MyComponent {
 @Input() someId: string = '1234';//default value
}

//HTML

<my-component someId="1234"></my-component>

"someId" is a optional input parameter that can be ignored as well.

EDIT: in a case where you are binding some constant string or number into an input it doesn't have to be specified in square brackets. You can use the same syntax as normal html attribute.

jo_va
  • 13,504
  • 3
  • 23
  • 47
Jeba Prince
  • 1,669
  • 4
  • 22
  • 41
  • I have injected the web component in react application. Passing attribute like this is not received in angular and it is returning `undefined`. Do you have any suggestion for that ? – I'm nidhin Jan 05 '23 at 07:14
0

I have had this issue about two days and finally I found the solution.

What you have to do is use the method ngOnChanges() in your component child (web component that you want to expose). Since this is to detect any change of your @Input() fields.

Here I leave a snippet code of my web component:

@Component({
  selector: 'app-shipment-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnChanges {

  @Input() domain;

  @Output() response = new EventEmitter<string>();

  constructor() {
  }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.domain) {
      console.log("Domain URL: ", this.domain);  
      this.response.emit(this.domain);
    }
  }

}
0

Not sure if your actual code looks like like this one, but in this particular example that you have provided, you can not detect sent string, nor will ngOnChanges fire a detection cycle.

If you are providing plain string to component, then you need to wrap it in simple quotes.

It has to be <my-component [someId]="'1234'"></my-component>

tony
  • 834
  • 5
  • 10