0
votes

i have a angular web component integrated in a normal html page. I want to pass an array of data which is in my html page to my web component.

    <script>
window.onload = function() {
  var myArray = [{value: 'aa', name: 'aaa'}, {value: 'bb', name:'bbb'}];
};</script>

now i want to pass "myArray" to my angular web component.

i have done like this. <someComponent [passdata]="myArray"></someComponent>

now in my component.ts page i have done

@Input() passdata: string;

and in ngOnInit i have consoled passdata, but i am not getting it. I am new to angular web components, if have done something wrong please help me.

2
don't know what your doing wrong here, hope the below answer will help you. If you want further help please attach your code - Vishnu Shenoy

2 Answers

0
votes

parent component.html

<child-component [myArray]="myArray"></child-component>

parent component.ts

public myArray = [{value: 'aa', name: 'aaa'}, {value: 'bb', name:'bbb'}];

child component.ts

@input() myArray;

ngOnChanges(){ console.log(myArray); }

Input example reference stackblitz

0
votes

Child component is initialized before the Input properties gets populated with the value. Therefore you are not getting the value in ngOnInit.

If you want to use the value only in template file, you can directly get it with @Input() like this -

 @Input() name: string;

and use it directly in html file like this -

<h1>Hello {{name}}!</h1> 

However if you want to get Input value in ngOnInit, you can use set method like this -

@Input()
  set myArray(value) {
    if(value) {
      this.array = value;
    }
  }

Here it first checks if value is not null/undefined, then it assigns the value to some local variable which can be used in the component itself.

You can see the running example here - InputExample (Check console to see the result)