How to trigger an update of NgComponent when child property changes

随声附和 提交于 2019-12-20 04:18:50

问题


I am a complete beginner to AngularDart (and Dart); I followed the tutorials but this is something I can't seem to find a answer to.

I have two NgComponents that work perfectly:

 <colorImage car-color="ctrl.car.color"></colorImage>
 <carImage car="ctrl.car"></carImage>

My controller "ctrl" has a property named "car" and "car" has a property named "color". When "car.color" changes, the colorButton NgComponent updates, but the carImage NgComponent does not.

How can I trigger an update of carImage when "car.color" changes?

Thanks!!


回答1:


You have to set a watch to car.color inside your CarImage. How this looks depends on what data structure you use for car.

// constructor
CarImage(Scope scope) {
   scope.$watch(() => car.color, (color) => doSomething(color));
}



回答2:


Here is working example without a scope and a watch features. I believe this is an angulardartish solution.

Something more about the issue: https://stackoverflow.com/a/21958268/2777805

ang_testi.dart

import 'package:angular/angular.dart';

@NgComponent(
 selector: 'colorImage',
 template: r'<p>colorImage: <input type="text" ng-model="cmp.carColor"></p>',
 publishAs: 'cmp'
)
class colorImage {
  @NgTwoWay('car-color')
  String carColor;
}

@NgComponent(
    selector: 'carImage',
    template: r'<p>carImage: <input type="text" ng-model="cmp.car.color"></p>',
    publishAs: 'cmp'
)
class carImage {
  @NgTwoWay('car')
  Map car;
}

@NgController(
    selector: '[main-test]',
    publishAs: 'ctrl')
class MainTestController {
  Map car = {"color":"green", "image":"someImage"};
}

class MyAppModule extends Module {
  MyAppModule() {
    type(MainTestController);
    type(colorImage);
    type(carImage);
  }
}

void main() {
  ngBootstrap(module: new MyAppModule());
}

ang_testi.html

<!DOCTYPE html>

<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>ng-model test</title>
    <link rel="stylesheet" href="ang_testi.css">
  </head>
  <body main-test>
    <colorImage car-color="ctrl.car.color"></colorImage> 
    <carImage car="ctrl.car"></carImage> 

    <p>controller: <input type="text" ng-model="ctrl.car.color"></p>
    <p>color is {{ctrl.car.color}}</p>

    <script src="packages/shadow_dom/shadow_dom.min.js"></script>
    <script type="application/dart" src="ang_testi.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>


来源:https://stackoverflow.com/questions/21773823/how-to-trigger-an-update-of-ngcomponent-when-child-property-changes

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