Angular form控件原生HTML代码里ng-reflect-form属性和其值的生成时机

举报
Jerry Wang 发表于 2022/04/25 16:16:33 2022/04/25
【摘要】 简单的Component代码:import { Component } from '@angular/core';import { FormControl } from '@angular/forms';@Component({ selector: 'app-reactive-favorite-color', template: ` Favorite Color: <input t...

简单的Component代码:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-favorite-color',
  template: `
    Favorite Color: <input type="text" [formControl]="favoriteColorControl">
  `
})
export class ReactFormComponent {
  favoriteColorControl = new FormControl('');
}

如下图所示:ng-reflect-form这个属性运行时是如何生成的?

bootstrap里调用_loadComponent:

changeDetectorRef的策略:RootViewRef:

ComponentRef指向的AppComponent,能看到Component的property:

loadComponent里显式调用tick:

tick函数里进行change detect:

Angular Component html里加了方括号的Directive,浏览器是无法识别的,在Angular core.js里,在执行Component template实现函数时,会调用Angular的ɵɵproperty函数,将中括号包裹的Angular指令展开:Update a property on a selected element.

element指向input控件:

需要添加到input标签页的属性名称为form:

经过normalizeDebugBindingValue里面的正则化处理完属性form之后,返回的值:

ng-reflect-form

待写入input ng-reflect-form属性的值:

为了避免value的值过于复杂时,序列化生成的json字符床过大,污染了最后的原生html,在normalizeDebugBindingValue里只是简单的调用toString函数:
// Limit the size of the value as otherwise the DOM just gets polluted.

这就是最后在Chrome开发者工具里看到的[object Object]的由来:

important takeaway

setNgReflectProperty函数

更多Jerry的原创文章,尽在:“汪子熙”:

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。