【问题标题】:External HTML Template interpolation外部 HTML 模板插值
【发布时间】:2017-07-18 21:16:58
【问题描述】:

我是 Angular 2.0 和 Angular 的新手。我已经在这个问题上挖掘了几天,我似乎在任何地方都找不到关于它的消息。我有一个在 TemplateURL 中调用外部 HTML 的组件,如下所示:

@Component({
  selector: 'Form-template',
  templateUrl: "app/components/HTMLReferences/CommentsForm.html",
  styleUrls: ["app/components/CSSReferences/CommentForm.css"]
  })

这里没什么疯狂的。

现在在我的模板中,我需要加载一个对象变量“频率”来填充下拉框。外部HTML模板里面的代码如下:

 <div class="dropdown">
    <select id="frequency"
            class="form-control"
            #frequency="ngModel"
            ngModel
            required>
      <option value=""></option>
      <option *ngFor="let frequency of frequencies" value="{{ frequency.id }}">
        {{frequency.label}}
      </option>
    </select>
  </div>

再一次,没什么特别的。该对象在组件的导出类中如下:

export class FormTemplateComponent  {
  frequencies = [
    { id: 1, label: 'Daily' },
    { id: 2, label: 'Weekly' },
    { id: 3, label: 'Monthly' }
  ];
}

当我加载页面时,下拉框中没有显示任何内容。这是屏幕截图:

我的 FromTemplateComponent 也可以在 NGModules 文件中的声明下找到。

我必须在这一切中遗漏一些非常愚蠢的东西,但我似乎无法弄清楚。想法?

【问题讨论】:

    标签: angular


    【解决方案1】:

    永远记住孩子:使用 ngModel 时,请确保正确设置名称。

    【讨论】:

      【解决方案2】:

      您应该使用如下属性绑定

      <div class="dropdown">
          <select id="frequency"
                  class="form-control"
                  [(ngModel)]="frequency"
                  required>
            <option value=""></option>
            <option *ngFor="let frequency of frequencies" [value]="frequency.id">
              {{frequency.label}}
            </option>
          </select>
      

      您可以在选择语句中使用(change) 事件作为记录和检查

      <select id="frequency" (change)="changed(frequency)">
      ....
      

      在下面的演示插件中可用

      LIVE DEMO

      【讨论】:

      • 这似乎无法解决问题。当我在同一个文件中声明所有内容时,我可以完成这项工作。问题来自于在 @component 装饰器上使用 TemplateURL: 属性。一旦我指向外部文件,一切都会中断。这几乎就像导出类中的频率对象没有被发送到我的外部 HTML 文件。
      • 发现问题了!鬼鬼祟祟的鬼鬼祟祟。我忘了设置名称=“频率”。原始代码有效。我只是个笨蛋。可以踢自己的胫骨。感谢您的帮助。我想我下次需要试试橡皮鸭调试。
      • 哎呀,估计没人会犯这样的错误。所以我的回答没用了?
      • 不是没用的。它使齿轮朝着新的方向旋转。看到我收到的针对新错误消息的错误消息点击了灯。非常感谢!
      • 酷然后快乐编码:)
      猜你喜欢
      • 2018-10-26
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      相关资源
      最近更新 更多