【问题标题】:how to make a delay for getting data in [(ngModel)]?如何延迟在 [(ngModel)] 中获取数据?
【发布时间】:2018-10-08 14:27:48
【问题描述】:

我在[(ngModel)] 中显示从服务器接收到的数据,但由于它们不会立即出现,因此我多次收到此错误:“ERROR TypeError: Cannot read property 'title' of undefined”。然后我的数据显示在输入字段中。

如何让数据只有收到才显示?

模板:

<form [formGroup]="angFormEd" novalidate>

        <input type="text" class="form-control" formControlName="titleEd"  #titleEd
               [(ngModel)]="post.title"/>

        <input type="url" class="form-control" formControlName="urlEd" #urlEd pattern="https?://.+"
               title="Include http://" [(ngModel)]="post.url"/>
 
        <button (click)="updatePost(titleEd.value, urlEd.value)"  
                [disabled]=" angFormEd.invalid">
                btn btn-primary">Update Post</button>     
    </form>

组件:

export class GalleryEditComponent implements OnInit {
    post: Picture;
    constructor(private fb: FormBuilder,
                private route: ActivatedRoute, private galleryService: GalleryService) {
    }

    ngOnInit() {
        this.editPost();
    }

    editPost(): void {
        this.route.params.subscribe(params => {
            this.galleryService.edit(params['id']).subscribe(res => {
                this.post = res;
            })
        })
    }

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您正在混合使用模板驱动表单和反应式表单,这是一种不好的做法。

    @Angular

    支持使用 ngModel 输入属性和 ngModelChange 事件 在 Angular v6 和 将在 Angular v7 中删除。

    选择patchValue()setValue()
    Updating Angular Forms with patchValue or setValue

    editPost(): void {
            this.route.params.subscribe(params => {
                this.galleryService.edit(params['id']).subscribe(res => {
                    this.post = res;
                    this.angFormEd.setValue({titleEd:res.title,urlEd:res.url})
                })
            })
        }
    

    【讨论】:

      【解决方案2】:

      您可以在输入中添加*ngIf="post.url" 之类的条件,以便仅在加载时显示

      【讨论】:

      • 好,不客气 :) 不要忘记标记已回答的问题以关闭主题 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多