dart:父母的数据将如何更改?

时间:2018-07-31 10:58:11

标签: dart angular-dart dart-html

我需要更改父母中的数据,如何正确处理?

父母

class Parent{
   int testText = 1;
}

孩子

class Child extends Parent{
   @Output()
   open(){
     int testText = 2;
   }
}

数据更改,但仅在子项中。如何更改父类中的数据?

2 个答案:

答案 0 :(得分:1)

@Output批注只能放在Stream数据结构上。所以你需要这样的东西:

class Child extends Parent{
   final _open = StreamController<int>();

   @Output()
   Stream get open => _open.stream;

   onOpen() { _open.add(2); }
}

在父模板中:

<child-comp (open)="testText = $event"></child-comp>

答案 1 :(得分:0)

如果我做对了,基本上您可以通过3种方式做到这一点:

1)使用一些将被注入到构造函数中的控制器,子代和父代都将监听并触发事件。

如果您想要更多类似组件的方式,则:

2)您可以使用数据绑定

<parent #myParent>
  <child (onSomething)="myParent.doSomething($event)"></child>
</parent>

在此解决方案中,您将在子组件中使用@Output()

3)您可以注入父组件(通过在父组件注释中添加visibility: Visibility.all,来确保父组件可见)。然后,您只需使用_parent.whatever()

@Component(
  selector: 'parent',
  styleUrls: ['...'],
  templateUrl: '...',
  directives: [...],
  visibility: Visibility.all,
)
class Parent implements OnInit {
  void doSomething() => print('yolo');

  List<Child> children = [];

  void registerChild(Child child) => children.add(child);
}

@Component(
  selector: 'child',
  styleUrls: ['...'],
  templateUrl: '...',
  directives: [...],
)
class Child implements OnInit {
  Parent _parent;

  Child(this._parent);

  @override
  void ngOnInit() {
    _parent?.registerChild(this);
  }

  @HostListener('click')
  void onClick() {
    _parent.doSomething();
  }
}