在reactive form中设置imge url在angular2+中出现错误。

问题描述 投票:1回答:1

我正在开发一个Angular应用程序,我已经成功地从数据库中获取了数据,并试图使用补丁值方法设置表单控件的值,但不幸的是,我得到了错误,即

core.js:6185 ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement'.这个输入元素接受一个文件名。这个输入元素接受一个文件名,它只能被编程设置为空字符串。

以下是我的代码 Snippet

组件.ts

 ngOnInit(): void {
this.EditForm();

this.GetValues() //method where I am retreiving data from firebase and iside it I am calling set Value

}
 EditForm() {


    this.exampleForm = this.fb.group({
      imgurl: ['',Validators.required],
      title: ['', Validators.required],
      desc: ['', Validators.required],
      category: [this.selected, Validators.required],
      subcategory: ['  ', Validators.required],
      name: ['', Validators.required],
      privacy: ["true"],
    });
  }

  setFormValue(d4) {
    this.imageSrc=d4.imgurl // this I have done to use string interpolation in template

    this.exampleForm.patchValue({
     imgurl:this.imageSrc,
      title:d4.title,
      desc:d4.desc,
      category:d4.category,
      name:d4.name,
      privacy:d4.privacy
    })
  }

组件.html

<div class="col-md-8 col-sm-9 col-xs-9">
    <form class="create-form" [formGroup]="exampleForm" novalidate (ngSubmit)="onSubmit(exampleForm.value)">

        <div class="col-md-4 col-sm-3 col-xs-12">
            <input type="file" multiple (change)="detectFiles($event) "
            accept="image/x-png,image/gif,image/jpeg" 
            class="form-control" 
             formControlName="imgurl">
            <img id="imgid"
             height="200" width="200" 
            class="img-rounded" 
             [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />

  </div>


//rest of form controls

但是当我看到我的提交按钮被禁用时,尽管所有的表单控件都有价值,当我在检查器中检查时,我发现img控制器有 无效. 我不知道是什么原因,请你帮帮我。

enter image description here

angular angular2-template angular-reactive-forms angular2-forms angular-forms
1个回答
1
投票

程式化地设置图像是不允许的,因为它可能会导致安全问题,并会对数据库产生严重的影响.所以你可以做的是按照我的答案。

Step1 component.ts

     EditForm() {
        this.exampleForm = this.fb.group({
          imgurl: [''],               // remove required validator so invalid will go away

        });
      }

    setFormValue(d4) {
        this.imageSrc=d4.imgurl   // string inerpollation
        this.downloadURL=d4.imgurl  //this value we will send to database
        this.exampleForm.patchValue({

          title:d4.title,
         ...// your other form values
        })
      }

      onSubmit(value: UPost) {

        this.yourservice.update(this.id, this.d4[this.id],value,this.downloadURL)
    }

serrvice.ts

update(id, value, formvalue, imgurl) {
    this.postdata = {
      title: formvalue.title,
       imgurl: imgurl,

      ...// your formvalues

    }
    console.log(value)

      this.http.patch(
        `https://write-your-heart-out-b338b.firebaseio.com/post/${this.uid}/public/${this.db_key}.json`, this.postdata)
        .subscribe()
    })
  }

希望对您有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.