我遇到的问题与此处提出的问题非常相似 How to add a component programatically in Angular.Dart? 。我正在使用 Angular Dart,并且有一个任务栏组件,我想用任务组件列表填充该组件。我希望在按下按钮时添加一个新的任务组件。这是我目前拥有的代码。
task_bar_component.html
<ul id="taskList" class="taskBar-items">
<li ng-repeat="task in taskbarCmp.tasks">
{{task}}
</li>
</ul>
task_bar_component.dart
@Component(
visibility: Directive.CHILDREN_VISIBILITY,
selector: 'taskbar',
templateUrl: '../lib/components/taskbar_component.html',
publishAs: 'taskbarCmp',
useShadowDom: false)
class TaskBarComponent {
List tasks;
TaskBarComponent() {
tasks = new List();
}
void addTask() {
var newTask = new TaskComponent();
tasks.add(newTask);
}
}
task_component.dart
@Component(
visibility: Directive.CHILDREN_VISIBILITY,
selector: 'task',
templateUrl: '../lib/components/task_component.html',
publishAs: 'taskCmp',
useShadowDom: false)
class TaskComponent {
bool _collapsed = true;
int _lopCount = 0;
int _geoCount = 0;
int _volume = 1;
String id;
TaskComponent() {
Collapse.use();
}
}
此代码当前在按钮单击时将“'TaskComponent'的实例”添加到 html,但它不包含实际的 task_component.html。我尝试使用上一个问题的解决方案中的 ShadowRootAware,但不确定按下按钮时如何调用 onShadowRoot。我还尝试使用该帖子中建议的指令解决方案,并且遇到了相同的问题,按下按钮时无法创建组件。如有任何建议,我们将不胜感激。
最佳答案
实际上,您的代码不起作用,因为
{{task}}
不要调用组件的 View ,它会尝试直接显示对象,但这不是您想要的。
要获得您想要的行为,您需要做更多类似的事情:
class Task {
// What you want in your task
}
@Component(
visibility: Directive.CHILDREN_VISIBILITY,
selector: 'task',
templateUrl: '../lib/components/task_component.html',
publishAs: 'taskCmp',
useShadowDom: false)
class TaskComponent {
@NgTwoWay('task')
Task task;
// What you want for you task view
TaskComponent() {
Collapse.use();
}
}
// task bar
class TaskBarComponent {
List<Task> tasks;
TaskBarComponent() {
tasks = new List();
}
void addTask() {
var newTask = new Task();
tasks.add(newTask);
}
}
在你的html中:
<ul id="taskList" class="taskBar-items">
<li ng-repeat="task in taskbarCmp.tasks">
<task task="task"></task>
</li>
</ul>
在这种情况下,您已经将逻辑与 View 完美分离,并获得了 Angular 组件的模块化
关于dart - 在 Angular Dart 中单击按钮动态创建和添加新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23948267/