input.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { coerceBooleanProperty } from '@angular/cdk/coercion';
  2. import * as i1 from '@angular/cdk/platform';
  3. import { getSupportedInputTypes } from '@angular/cdk/platform';
  4. import * as i4 from '@angular/cdk/text-field';
  5. import { TextFieldModule } from '@angular/cdk/text-field';
  6. import * as i0 from '@angular/core';
  7. import { InjectionToken, Directive, Optional, Self, Inject, Input, NgModule } from '@angular/core';
  8. import * as i2 from '@angular/forms';
  9. import { Validators } from '@angular/forms';
  10. import * as i3 from '@angular/material/core';
  11. import { mixinErrorState, MatCommonModule } from '@angular/material/core';
  12. import * as i5 from '@angular/material/form-field';
  13. import { MAT_FORM_FIELD, MatFormFieldControl, MatFormFieldModule } from '@angular/material/form-field';
  14. import { Subject } from 'rxjs';
  15. /** @docs-private */
  16. function getMatInputUnsupportedTypeError(type) {
  17. return Error(`Input type "${type}" isn't supported by matInput.`);
  18. }
  19. /**
  20. * This token is used to inject the object whose value should be set into `MatInput`. If none is
  21. * provided, the native `HTMLInputElement` is used. Directives like `MatDatepickerInput` can provide
  22. * themselves for this token, in order to make `MatInput` delegate the getting and setting of the
  23. * value to them.
  24. */
  25. const MAT_INPUT_VALUE_ACCESSOR = new InjectionToken('MAT_INPUT_VALUE_ACCESSOR');
  26. // Invalid input type. Using one of these will throw an MatInputUnsupportedTypeError.
  27. const MAT_INPUT_INVALID_TYPES = [
  28. 'button',
  29. 'checkbox',
  30. 'file',
  31. 'hidden',
  32. 'image',
  33. 'radio',
  34. 'range',
  35. 'reset',
  36. 'submit',
  37. ];
  38. let nextUniqueId = 0;
  39. // Boilerplate for applying mixins to MatInput.
  40. /** @docs-private */
  41. const _MatInputBase = mixinErrorState(class {
  42. constructor(_defaultErrorStateMatcher, _parentForm, _parentFormGroup,
  43. /**
  44. * Form control bound to the component.
  45. * Implemented as part of `MatFormFieldControl`.
  46. * @docs-private
  47. */
  48. ngControl) {
  49. this._defaultErrorStateMatcher = _defaultErrorStateMatcher;
  50. this._parentForm = _parentForm;
  51. this._parentFormGroup = _parentFormGroup;
  52. this.ngControl = ngControl;
  53. /**
  54. * Emits whenever the component state changes and should cause the parent
  55. * form field to update. Implemented as part of `MatFormFieldControl`.
  56. * @docs-private
  57. */
  58. this.stateChanges = new Subject();
  59. }
  60. });
  61. class MatInput extends _MatInputBase {
  62. /**
  63. * Implemented as part of MatFormFieldControl.
  64. * @docs-private
  65. */
  66. get disabled() {
  67. return this._disabled;
  68. }
  69. set disabled(value) {
  70. this._disabled = coerceBooleanProperty(value);
  71. // Browsers may not fire the blur event if the input is disabled too quickly.
  72. // Reset from here to ensure that the element doesn't become stuck.
  73. if (this.focused) {
  74. this.focused = false;
  75. this.stateChanges.next();
  76. }
  77. }
  78. /**
  79. * Implemented as part of MatFormFieldControl.
  80. * @docs-private
  81. */
  82. get id() {
  83. return this._id;
  84. }
  85. set id(value) {
  86. this._id = value || this._uid;
  87. }
  88. /**
  89. * Implemented as part of MatFormFieldControl.
  90. * @docs-private
  91. */
  92. get required() {
  93. return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
  94. }
  95. set required(value) {
  96. this._required = coerceBooleanProperty(value);
  97. }
  98. /** Input type of the element. */
  99. get type() {
  100. return this._type;
  101. }
  102. set type(value) {
  103. this._type = value || 'text';
  104. this._validateType();
  105. // When using Angular inputs, developers are no longer able to set the properties on the native
  106. // input element. To ensure that bindings for `type` work, we need to sync the setter
  107. // with the native property. Textarea elements don't support the type property or attribute.
  108. if (!this._isTextarea && getSupportedInputTypes().has(this._type)) {
  109. this._elementRef.nativeElement.type = this._type;
  110. }
  111. }
  112. /**
  113. * Implemented as part of MatFormFieldControl.
  114. * @docs-private
  115. */
  116. get value() {
  117. return this._inputValueAccessor.value;
  118. }
  119. set value(value) {
  120. if (value !== this.value) {
  121. this._inputValueAccessor.value = value;
  122. this.stateChanges.next();
  123. }
  124. }
  125. /** Whether the element is readonly. */
  126. get readonly() {
  127. return this._readonly;
  128. }
  129. set readonly(value) {
  130. this._readonly = coerceBooleanProperty(value);
  131. }
  132. constructor(_elementRef, _platform, ngControl, _parentForm, _parentFormGroup, _defaultErrorStateMatcher, inputValueAccessor, _autofillMonitor, ngZone,
  133. // TODO: Remove this once the legacy appearance has been removed. We only need
  134. // to inject the form field for determining whether the placeholder has been promoted.
  135. _formField) {
  136. super(_defaultErrorStateMatcher, _parentForm, _parentFormGroup, ngControl);
  137. this._elementRef = _elementRef;
  138. this._platform = _platform;
  139. this._autofillMonitor = _autofillMonitor;
  140. this._formField = _formField;
  141. this._uid = `mat-input-${nextUniqueId++}`;
  142. /**
  143. * Implemented as part of MatFormFieldControl.
  144. * @docs-private
  145. */
  146. this.focused = false;
  147. /**
  148. * Implemented as part of MatFormFieldControl.
  149. * @docs-private
  150. */
  151. this.stateChanges = new Subject();
  152. /**
  153. * Implemented as part of MatFormFieldControl.
  154. * @docs-private
  155. */
  156. this.controlType = 'mat-input';
  157. /**
  158. * Implemented as part of MatFormFieldControl.
  159. * @docs-private
  160. */
  161. this.autofilled = false;
  162. this._disabled = false;
  163. this._type = 'text';
  164. this._readonly = false;
  165. this._neverEmptyInputTypes = [
  166. 'date',
  167. 'datetime',
  168. 'datetime-local',
  169. 'month',
  170. 'time',
  171. 'week',
  172. ].filter(t => getSupportedInputTypes().has(t));
  173. this._iOSKeyupListener = (event) => {
  174. const el = event.target;
  175. // Note: We specifically check for 0, rather than `!el.selectionStart`, because the two
  176. // indicate different things. If the value is 0, it means that the caret is at the start
  177. // of the input, whereas a value of `null` means that the input doesn't support
  178. // manipulating the selection range. Inputs that don't support setting the selection range
  179. // will throw an error so we want to avoid calling `setSelectionRange` on them. See:
  180. // https://html.spec.whatwg.org/multipage/input.html#do-not-apply
  181. if (!el.value && el.selectionStart === 0 && el.selectionEnd === 0) {
  182. // Note: Just setting `0, 0` doesn't fix the issue. Setting
  183. // `1, 1` fixes it for the first time that you type text and
  184. // then hold delete. Toggling to `1, 1` and then back to
  185. // `0, 0` seems to completely fix it.
  186. el.setSelectionRange(1, 1);
  187. el.setSelectionRange(0, 0);
  188. }
  189. };
  190. const element = this._elementRef.nativeElement;
  191. const nodeName = element.nodeName.toLowerCase();
  192. // If no input value accessor was explicitly specified, use the element as the input value
  193. // accessor.
  194. this._inputValueAccessor = inputValueAccessor || element;
  195. this._previousNativeValue = this.value;
  196. // Force setter to be called in case id was not specified.
  197. this.id = this.id;
  198. // On some versions of iOS the caret gets stuck in the wrong place when holding down the delete
  199. // key. In order to get around this we need to "jiggle" the caret loose. Since this bug only
  200. // exists on iOS, we only bother to install the listener on iOS.
  201. if (_platform.IOS) {
  202. ngZone.runOutsideAngular(() => {
  203. _elementRef.nativeElement.addEventListener('keyup', this._iOSKeyupListener);
  204. });
  205. }
  206. this._isServer = !this._platform.isBrowser;
  207. this._isNativeSelect = nodeName === 'select';
  208. this._isTextarea = nodeName === 'textarea';
  209. this._isInFormField = !!_formField;
  210. if (this._isNativeSelect) {
  211. this.controlType = element.multiple
  212. ? 'mat-native-select-multiple'
  213. : 'mat-native-select';
  214. }
  215. }
  216. ngAfterViewInit() {
  217. if (this._platform.isBrowser) {
  218. this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(event => {
  219. this.autofilled = event.isAutofilled;
  220. this.stateChanges.next();
  221. });
  222. }
  223. }
  224. ngOnChanges() {
  225. this.stateChanges.next();
  226. }
  227. ngOnDestroy() {
  228. this.stateChanges.complete();
  229. if (this._platform.isBrowser) {
  230. this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement);
  231. }
  232. if (this._platform.IOS) {
  233. this._elementRef.nativeElement.removeEventListener('keyup', this._iOSKeyupListener);
  234. }
  235. }
  236. ngDoCheck() {
  237. if (this.ngControl) {
  238. // We need to re-evaluate this on every change detection cycle, because there are some
  239. // error triggers that we can't subscribe to (e.g. parent form submissions). This means
  240. // that whatever logic is in here has to be super lean or we risk destroying the performance.
  241. this.updateErrorState();
  242. // Since the input isn't a `ControlValueAccessor`, we don't have a good way of knowing when
  243. // the disabled state has changed. We can't use the `ngControl.statusChanges`, because it
  244. // won't fire if the input is disabled with `emitEvents = false`, despite the input becoming
  245. // disabled.
  246. if (this.ngControl.disabled !== null && this.ngControl.disabled !== this.disabled) {
  247. this.disabled = this.ngControl.disabled;
  248. this.stateChanges.next();
  249. }
  250. }
  251. // We need to dirty-check the native element's value, because there are some cases where
  252. // we won't be notified when it changes (e.g. the consumer isn't using forms or they're
  253. // updating the value using `emitEvent: false`).
  254. this._dirtyCheckNativeValue();
  255. // We need to dirty-check and set the placeholder attribute ourselves, because whether it's
  256. // present or not depends on a query which is prone to "changed after checked" errors.
  257. this._dirtyCheckPlaceholder();
  258. }
  259. /** Focuses the input. */
  260. focus(options) {
  261. this._elementRef.nativeElement.focus(options);
  262. }
  263. /** Callback for the cases where the focused state of the input changes. */
  264. _focusChanged(isFocused) {
  265. if (isFocused !== this.focused) {
  266. this.focused = isFocused;
  267. this.stateChanges.next();
  268. }
  269. }
  270. _onInput() {
  271. // This is a noop function and is used to let Angular know whenever the value changes.
  272. // Angular will run a new change detection each time the `input` event has been dispatched.
  273. // It's necessary that Angular recognizes the value change, because when floatingLabel
  274. // is set to false and Angular forms aren't used, the placeholder won't recognize the
  275. // value changes and will not disappear.
  276. // Listening to the input event wouldn't be necessary when the input is using the
  277. // FormsModule or ReactiveFormsModule, because Angular forms also listens to input events.
  278. }
  279. /** Does some manual dirty checking on the native input `value` property. */
  280. _dirtyCheckNativeValue() {
  281. const newValue = this._elementRef.nativeElement.value;
  282. if (this._previousNativeValue !== newValue) {
  283. this._previousNativeValue = newValue;
  284. this.stateChanges.next();
  285. }
  286. }
  287. /** Does some manual dirty checking on the native input `placeholder` attribute. */
  288. _dirtyCheckPlaceholder() {
  289. const placeholder = this._getPlaceholder();
  290. if (placeholder !== this._previousPlaceholder) {
  291. const element = this._elementRef.nativeElement;
  292. this._previousPlaceholder = placeholder;
  293. placeholder
  294. ? element.setAttribute('placeholder', placeholder)
  295. : element.removeAttribute('placeholder');
  296. }
  297. }
  298. /** Gets the current placeholder of the form field. */
  299. _getPlaceholder() {
  300. return this.placeholder || null;
  301. }
  302. /** Make sure the input is a supported type. */
  303. _validateType() {
  304. if (MAT_INPUT_INVALID_TYPES.indexOf(this._type) > -1 &&
  305. (typeof ngDevMode === 'undefined' || ngDevMode)) {
  306. throw getMatInputUnsupportedTypeError(this._type);
  307. }
  308. }
  309. /** Checks whether the input type is one of the types that are never empty. */
  310. _isNeverEmpty() {
  311. return this._neverEmptyInputTypes.indexOf(this._type) > -1;
  312. }
  313. /** Checks whether the input is invalid based on the native validation. */
  314. _isBadInput() {
  315. // The `validity` property won't be present on platform-server.
  316. let validity = this._elementRef.nativeElement.validity;
  317. return validity && validity.badInput;
  318. }
  319. /**
  320. * Implemented as part of MatFormFieldControl.
  321. * @docs-private
  322. */
  323. get empty() {
  324. return (!this._isNeverEmpty() &&
  325. !this._elementRef.nativeElement.value &&
  326. !this._isBadInput() &&
  327. !this.autofilled);
  328. }
  329. /**
  330. * Implemented as part of MatFormFieldControl.
  331. * @docs-private
  332. */
  333. get shouldLabelFloat() {
  334. if (this._isNativeSelect) {
  335. // For a single-selection `<select>`, the label should float when the selected option has
  336. // a non-empty display value. For a `<select multiple>`, the label *always* floats to avoid
  337. // overlapping the label with the options.
  338. const selectElement = this._elementRef.nativeElement;
  339. const firstOption = selectElement.options[0];
  340. // On most browsers the `selectedIndex` will always be 0, however on IE and Edge it'll be
  341. // -1 if the `value` is set to something, that isn't in the list of options, at a later point.
  342. return (this.focused ||
  343. selectElement.multiple ||
  344. !this.empty ||
  345. !!(selectElement.selectedIndex > -1 && firstOption && firstOption.label));
  346. }
  347. else {
  348. return this.focused || !this.empty;
  349. }
  350. }
  351. /**
  352. * Implemented as part of MatFormFieldControl.
  353. * @docs-private
  354. */
  355. setDescribedByIds(ids) {
  356. if (ids.length) {
  357. this._elementRef.nativeElement.setAttribute('aria-describedby', ids.join(' '));
  358. }
  359. else {
  360. this._elementRef.nativeElement.removeAttribute('aria-describedby');
  361. }
  362. }
  363. /**
  364. * Implemented as part of MatFormFieldControl.
  365. * @docs-private
  366. */
  367. onContainerClick() {
  368. // Do not re-focus the input element if the element is already focused. Otherwise it can happen
  369. // that someone clicks on a time input and the cursor resets to the "hours" field while the
  370. // "minutes" field was actually clicked. See: https://github.com/angular/components/issues/12849
  371. if (!this.focused) {
  372. this.focus();
  373. }
  374. }
  375. /** Whether the form control is a native select that is displayed inline. */
  376. _isInlineSelect() {
  377. const element = this._elementRef.nativeElement;
  378. return this._isNativeSelect && (element.multiple || element.size > 1);
  379. }
  380. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatInput, deps: [{ token: i0.ElementRef }, { token: i1.Platform }, { token: i2.NgControl, optional: true, self: true }, { token: i2.NgForm, optional: true }, { token: i2.FormGroupDirective, optional: true }, { token: i3.ErrorStateMatcher }, { token: MAT_INPUT_VALUE_ACCESSOR, optional: true, self: true }, { token: i4.AutofillMonitor }, { token: i0.NgZone }, { token: MAT_FORM_FIELD, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  381. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],\n input[matNativeControl], textarea[matNativeControl]", inputs: { disabled: "disabled", id: "id", placeholder: "placeholder", name: "name", required: "required", type: "type", errorStateMatcher: "errorStateMatcher", userAriaDescribedBy: ["aria-describedby", "userAriaDescribedBy"], value: "value", readonly: "readonly" }, host: { listeners: { "focus": "_focusChanged(true)", "blur": "_focusChanged(false)", "input": "_onInput()" }, properties: { "class.mat-input-server": "_isServer", "class.mat-mdc-form-field-textarea-control": "_isInFormField && _isTextarea", "class.mat-mdc-form-field-input-control": "_isInFormField", "class.mdc-text-field__input": "_isInFormField", "class.mat-mdc-native-select-inline": "_isInlineSelect()", "id": "id", "disabled": "disabled", "required": "required", "attr.name": "name || null", "attr.readonly": "readonly && !_isNativeSelect || null", "attr.aria-invalid": "(empty && required) ? null : errorState", "attr.aria-required": "required", "attr.id": "id" }, classAttribute: "mat-mdc-input-element" }, providers: [{ provide: MatFormFieldControl, useExisting: MatInput }], exportAs: ["matInput"], usesInheritance: true, usesOnChanges: true, ngImport: i0 }); }
  382. }
  383. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatInput, decorators: [{
  384. type: Directive,
  385. args: [{
  386. selector: `input[matInput], textarea[matInput], select[matNativeControl],
  387. input[matNativeControl], textarea[matNativeControl]`,
  388. exportAs: 'matInput',
  389. host: {
  390. 'class': 'mat-mdc-input-element',
  391. // The BaseMatInput parent class adds `mat-input-element`, `mat-form-field-control` and
  392. // `mat-form-field-autofill-control` to the CSS class list, but this should not be added for
  393. // this MDC equivalent input.
  394. '[class.mat-input-server]': '_isServer',
  395. '[class.mat-mdc-form-field-textarea-control]': '_isInFormField && _isTextarea',
  396. '[class.mat-mdc-form-field-input-control]': '_isInFormField',
  397. '[class.mdc-text-field__input]': '_isInFormField',
  398. '[class.mat-mdc-native-select-inline]': '_isInlineSelect()',
  399. // Native input properties that are overwritten by Angular inputs need to be synced with
  400. // the native input element. Otherwise property bindings for those don't work.
  401. '[id]': 'id',
  402. '[disabled]': 'disabled',
  403. '[required]': 'required',
  404. '[attr.name]': 'name || null',
  405. '[attr.readonly]': 'readonly && !_isNativeSelect || null',
  406. // Only mark the input as invalid for assistive technology if it has a value since the
  407. // state usually overlaps with `aria-required` when the input is empty and can be redundant.
  408. '[attr.aria-invalid]': '(empty && required) ? null : errorState',
  409. '[attr.aria-required]': 'required',
  410. // Native input properties that are overwritten by Angular inputs need to be synced with
  411. // the native input element. Otherwise property bindings for those don't work.
  412. '[attr.id]': 'id',
  413. '(focus)': '_focusChanged(true)',
  414. '(blur)': '_focusChanged(false)',
  415. '(input)': '_onInput()',
  416. },
  417. providers: [{ provide: MatFormFieldControl, useExisting: MatInput }],
  418. }]
  419. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1.Platform }, { type: i2.NgControl, decorators: [{
  420. type: Optional
  421. }, {
  422. type: Self
  423. }] }, { type: i2.NgForm, decorators: [{
  424. type: Optional
  425. }] }, { type: i2.FormGroupDirective, decorators: [{
  426. type: Optional
  427. }] }, { type: i3.ErrorStateMatcher }, { type: undefined, decorators: [{
  428. type: Optional
  429. }, {
  430. type: Self
  431. }, {
  432. type: Inject,
  433. args: [MAT_INPUT_VALUE_ACCESSOR]
  434. }] }, { type: i4.AutofillMonitor }, { type: i0.NgZone }, { type: i5.MatFormField, decorators: [{
  435. type: Optional
  436. }, {
  437. type: Inject,
  438. args: [MAT_FORM_FIELD]
  439. }] }]; }, propDecorators: { disabled: [{
  440. type: Input
  441. }], id: [{
  442. type: Input
  443. }], placeholder: [{
  444. type: Input
  445. }], name: [{
  446. type: Input
  447. }], required: [{
  448. type: Input
  449. }], type: [{
  450. type: Input
  451. }], errorStateMatcher: [{
  452. type: Input
  453. }], userAriaDescribedBy: [{
  454. type: Input,
  455. args: ['aria-describedby']
  456. }], value: [{
  457. type: Input
  458. }], readonly: [{
  459. type: Input
  460. }] } });
  461. class MatInputModule {
  462. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatInputModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
  463. static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.0", ngImport: i0, type: MatInputModule, declarations: [MatInput], imports: [MatCommonModule, MatFormFieldModule], exports: [MatInput, MatFormFieldModule, TextFieldModule, MatCommonModule] }); }
  464. static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatInputModule, imports: [MatCommonModule, MatFormFieldModule, MatFormFieldModule, TextFieldModule, MatCommonModule] }); }
  465. }
  466. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatInputModule, decorators: [{
  467. type: NgModule,
  468. args: [{
  469. imports: [MatCommonModule, MatFormFieldModule],
  470. exports: [MatInput, MatFormFieldModule, TextFieldModule, MatCommonModule],
  471. declarations: [MatInput],
  472. }]
  473. }] });
  474. /**
  475. * Generated bundle index. Do not edit.
  476. */
  477. export { MAT_INPUT_VALUE_ACCESSOR, MatInput, MatInputModule, getMatInputUnsupportedTypeError };
  478. //# sourceMappingURL=input.mjs.map