Use DartAngular with dart:html

China☆狼群 提交于 2019-12-24 01:57:32

问题


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.


回答1:


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)




回答2:


EDIT: If someone like me want to use dart:html instead angular ng code, it's possible to use it

import 'package:angular/angular.dart';
import 'dart:html';

// AngularDart info: https://webdev.dartlang.org/angular
// Components info: https://webdev.dartlang.org/components

@Component(
  selector: 'container',
  template: '<h1>Test 1</h1><button #test1>Bottone test 1</button>',
)
class Test1Component implements OnInit{

  @ViewChild('test1')
  ButtonElement button;


  @override
  void ngOnInit() {
    //Verified that button is initialized
    print(button);
    //Initialize click
    button.onClick.listen((e) => print("Clicked"));
  }
}


来源:https://stackoverflow.com/questions/51969903/use-dartangular-with-darthtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!