【问题标题】:reference img in Angular2 form with typescript使用打字稿以 Angular2 形式引用 img
【发布时间】:2016-12-09 19:02:55
【问题描述】:

我正在从我的模板向我的 angular2 发布一个带有其名称的图像。

我从我的机器中选择图像:

<input type="file" multiple (change)="fileChange(input)" #input />

fileChange 方法正在接收文件并将其保存在下面的 img 标签中,所以当我准备提交表单时,它就在那里:

<form [formGroup]="myForm" (ngSubmit)="submit()">
    <img [attr.src]='src' alt="" id="myphoto" name="myphoto" [formControl]="myphoto" />
    <input type="text" id="photoname" name="photoname" [formControl]="photoname" />
    <label for="photoname">Name</label>
</form>

在我的 photo.ts 中

import { Component, OnInit, ChangeDetectorRef } from "@angular/core";
.....
import { FormBuilder, FormControl, FormGroup} from "@angular/forms";

@Component({
  // selector and templateurl
})

export class SendMyPhoto {
    myForm: FormGroup;
    ....
    constructor(builder: FormBuilder) {
      this.photoname = new FormControl("", []);
      this.myphoto= new FormControl("", []);

      this.myForm= builder.group({
        photoname: this.photoname,
        myphoto: this.myphoto
      });
    }

当我从我的机器中选择图像时,我收到此错误并且图像不显示:

core.umd.js:2838 例外:错误 /js/app/templates/myphoto.html:22:88 原因:没有值访问器 名称为“myphoto”的表单控件

如果我删除了

[formControl]="myphoto"

图像显示正常,没有错误,但是我无法在 typescript 的 formbuilder 中引用它,因此我可以将其发送到我的服务器。

我已经尝试过使用 formcontrolname 而不是 [formControl] 但行为没有区别

【问题讨论】:

  • 您是否使用 img 标签上传图片?如何?它是一个组件吗?你不需要使用 吗?对于图片上传,您必须在表单中设置enctype="multipart/form-data"
  • @vinagreti 我更新问题来回答你的问题
  • 可能是:ìmg 标签不是有效输入,因此其中没有formControl 的实现。这就是您收到错误的原因。第二件事是(我认为)您在将input 转换为img 标记之前将src 值分配给变量,这就是删除formControl 时图像显示的原因。所以,我认为你应该从变量中获取src,而不是从formControl。你怎么看?
  • 是的,实际上这就是我现在使用 getElementById 所做的事情。如果这是唯一的方法,那就这样吧。请发表您的评论,我会将其设置为答案。

标签: angular typescript materialize


【解决方案1】:

可能是:ìmg标签不是一个有效的输入,所以里面没有formControl的实现。这就是您收到错误的原因。第二件事是(我认为)您在将输入转换为 img 标记之前将 src 值分配给变量,这就是删除 formControl 时图像显示的原因。所以,我认为你应该从变量而不是从 formControl 中获取 src。你怎么看?

您可以实现一个图像输入组件,并使用 ngmodel 来获取图像数据。

http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2016-12-02
    • 1970-01-01
    相关资源
    最近更新 更多