【问题标题】:I have a few text boxes that fill when I type in one我有几个文本框在我输入一个时会填满
【发布时间】:2019-06-16 14:49:00
【问题描述】:

我正在创建一个动态表单,允许用户指定问题可以是什么以及存储在 Google Firestore 集合中的问题数量。当我填写一个文本框时,其他文本框会充满完全相同的内容。

html 文件:这将创建表单并使用角度表单模块。 添加项目

  <ul *ngFor="let question of questions">
    <li><strong>{{question.name}}</strong>
      <input type="text" placeholder="Add Title" [(ngModel)] = 'answer.name' name = "title">
    </li>
  </ul>

  <input type="submit" value = "Submit" class = "btn">
</form>

ts 文件:ts 文件从数据服务中获取数据并将 tha 提供给 html。

@Component({
  selector: 'app-add-item',
  templateUrl: './add-item.component.html',
  styleUrls: ['./add-item.component.scss']
})
export class AddItemComponent implements OnInit {
  questions: Question[];
  items: Item[];
  answers: Answer[];
  answer: Answer = {
    name:'',
    number:0

  }
  item: Item = {
    title:'',
    description:'',

  }
  question: Question = {
    name:'',
    number:null,
    answer:'',
  }
  database;
  doc:'';


  constructor(private dataService: DataService, private route: ActivatedRoute) { 
    this.route.params.subscribe(params => this.doc = params["id"])

  }

  ngOnInit() {
    this.dataService.getQuestions(this.doc).subscribe(questions => {
      this.questions = questions;
    })
  }
  onSubmit(){
{
  if(this.answer.name != ''){
    console.log(this.answer.name)
    this.dataService.addAnswer(this.answer);
    this.answer.name = "";


    }


  }

}}

预计文本框会单独填充,我可以记录它们的数据。

实际上是同时填充所有文本框。

【问题讨论】:

  • 这可能是因为,所有输入框都绑定了相同的ngModel

标签: javascript angular google-cloud-firestore angularfire2


【解决方案1】:

您可以通过以下方式从文本框中获取单独的值

 <ul *ngFor="let question of questions">
<li><strong>{{question.name}}</strong>
  <input type="text" placeholder="Add Title" [(ngModel)] = 'question.answer' name = "title">
</li>

【讨论】:

  • 为什么会有不同?我想将答案与所有​​其他答案一起存储在与问题集合分开的集合中。抱歉,我对 Angular 和 Firestore 有点陌生。
  • 不同之处在于您将同一个对象与所有文本框相关联。
【解决方案2】:

&lt;ul *ngFor="let question of questions"&gt;&lt;li&gt;&lt;strong&gt;{{question.name}}&lt;/strong&gt;&lt;input type="text" placeholder="Add Title" [(ngModel)] = 'question.answer' name =title[]&gt;&lt;/li&gt;

【讨论】:

  • 代码看起来很完美。请考虑添加一些 cmets 来描述您的代码要完成的工作。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2014-12-13
  • 1970-01-01
  • 2017-11-17
相关资源
最近更新 更多