【问题标题】:HTML selected is not working with Angular 6选择的 HTML 不适用于 Angular 6
【发布时间】:2019-07-17 16:57:04
【问题描述】:

我正在使用 Angular,

在我的模板中,枚举硬编码为可能的值:

<div class="col-lg-9">
  <select id="content_type_select" name="content_type"  class="form-control multiselect-select-one" [(ngModel)]="selectedContent.contentType" data-fouc>
    <option [selected]="selectedContent.contentType===ContentType.Image" [value]="ContentType.Image">Image</option>
    <option [selected]="selectedContent.contentType===ContentType.Video" [value]="ContentType.Video">Video</option>
    <option [selected]="selectedContent.contentType===ContentType.Text"  [value]="ContentType.Text">Txt</option>
    <option [selected]="selectedContent.contentType===ContentType.HTML"  [value]="ContentType.HTML">HTML</option>
  </select>
</div>

在我的打字稿中,我将 selectedContent 发送到模板,并且我已经登录 cosole 以检查我的 selectedContent 的值,它看起来像这样:

正如你所看到的,当我console.log(this.selectedContent) 有属性contentType 的值为 1 并且在我的下拉列表中应该选择图像,但实际上没有选择任何内容..

但是如果我写[selected]="true",那么这个选项就会被选中...怎么来的:/

谢谢大家

干杯

【问题讨论】:

  • 你从哪里得到ContentType.Image ContentType.Video 等等...? Surly if content type 1 === Image 你的代码应该是[selected]="selectedContent.contentType===1"
  • 在控制台日志中,您正在获取数字尝试在HTML 处将ContentType.Image 替换为1,我认为它会起作用。

标签: javascript html angular select drop-down-menu


【解决方案1】:

我认为您需要提供更多上下文(例如 ContentType 枚举的实现)。但是,让我为您提供此类问题的一些常用答案。

枚举不会自动在模板上可用,因为它们是在组件的类中导入的。假设你有一个像

这样的枚举
export enum ContentType {
  Image = 1,
  Video = 2,
  Text = 3,
  HTML = 4
}

如果您需要从模板中使用它,它必须首先与一些公开可用的类属性相关联,例如public readonly contentType = ContentType 然后在模板代码上这样引用:

<select id="content_type_select" name="content_type"  class="form-control multiselect-select-one" [(ngModel)]="selectedContent.contentType" data-fouc>
    <option [selected]="selectedContent.contentType === contentType.Image" [value]="contentType.Image">Image</option>
    <option [selected]="selectedContent.contentType === contentType.Video" [value]="contentType.Video">Video</option>
    <option [selected]="selectedContent.contentType === contentType.Text"  [value]="contentType.Text">Txt</option>
    <option [selected]="selectedContent.contentType === contentType.HTML"  [value]="contentType.HTML">HTML</option>
  </select>

此外,请注意 JavaScript 类型,因为正在使用身份运算符。 1 == "1"1 !== '1'

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多