Use DartAngular with dart:html

Issue

Is it possible to use default dart library html with angular dart?
ie:

class Test1Component implements OnInit{
  @override
  void ngOnInit() {
    ButtonElement button = querySelector('button');
    //Broken code, avoid button to be null.
    button.onClick.listen(onClick);
  }

  void onClick(Event e){
    print('Button clicked');
  }
}

How can I avoid to get a ‘null’ button without the using any timers?

Basically I’m using only angular just for the Routes and but I’d like to stick with dart:html to control the DOM and events.

Solution

Yes, you can do that, but it’s usually not a good idea.

Use instead @ViewChild(...) or similar Angular methods to get references to elements in a components view.

<button #myButton>click me</button>
@ViewChildren('myButton')
set myButton(List<Element> value) {
  if(value.isNotEmpty) {
    print(value.first);
  }
}

If you want to just add a click handler using

<button (click)="onClick">click me</button>

would be the better way but it sounds you are somehow adding the button dynamically and adding a click handler declaratively might not work in this case (would need more info)

Answered By – Günter Zöchbauer

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *