Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29149

Set property from outside Angular on Angular component

I have an Angular component as follows

@Component({
  selector: 'app-data-view',
  templateUrl: './data-view.component.html',
  styleUrls: ['./data-view.component.scss']
})
export class DataViewComponent implements OnInit, OnChanges {
  @Input() data = { val: 1 };
  ...
}

I would like to set data on that component from outside of Angular, so I did

const el = document.querySelector('app-data-view');
console.log(el.data);  // -> undefined
el.data = { val: 2 };  // -> nothing happens

That didn't work, and nothing happened. The only thing that seems to work is with dispatchEvent and @HostListener. But I was wondering if I'm doing something wrong in my above example?

Upvotes: 0

Views: 987

Answers (1)

John Smith
John Smith

Reputation: 1110

You have to get the component instance not HTML DOM element

To get component instance type in the console:

ng.probe(document.querySelector('app-data-view')); // returns Angular Component

Read more here: https://juristr.com/blog/2016/02/debugging-angular2-console/

Unless you write dev tools, you MUST NOT change the state of the angular component in this way.

Upvotes: 1

Related Questions