From e25c6ba659347c34bbf822cf495eb2e0d1b59994 Mon Sep 17 00:00:00 2001 From: Wendell Date: Thu, 21 Mar 2019 11:24:12 +0800 Subject: [PATCH] chore: adopt prettier code formatter (#3129) * chore: adopt prettier code formatter * chore: add less as ignored * fix: fix tsconfig * fix: unmerged file * fix: lint * fix: lint --- .prettierignore | 10 + .prettierrc | 14 + components/affix/affix.spec.ts | 45 +- components/affix/demo/basic.ts | 29 +- components/affix/demo/on-change.ts | 8 +- components/affix/demo/target.ts | 40 +- components/affix/nz-affix.component.ts | 80 +- components/affix/nz-affix.module.ts | 11 +- components/alert/demo/banner.ts | 13 +- components/alert/demo/basic.ts | 7 +- components/alert/demo/closable.ts | 10 +- components/alert/demo/close-text.ts | 3 +- components/alert/demo/description.ts | 17 +- components/alert/demo/icon.ts | 20 +- components/alert/demo/style.ts | 7 +- components/alert/nz-alert.component.ts | 20 +- components/alert/nz-alert.module.ts | 9 +- components/alert/nz-alert.spec.ts | 15 +- components/anchor/anchor.spec.ts | 109 +- components/anchor/demo/basic.ts | 2 +- components/anchor/demo/static.ts | 7 +- components/anchor/nz-anchor-link.component.ts | 34 +- components/anchor/nz-anchor.component.ts | 25 +- components/anchor/nz-anchor.module.ts | 11 +- components/auto-complete/demo/basic.ts | 26 +- .../auto-complete/demo/certain-category.ts | 106 +- components/auto-complete/demo/custom.ts | 23 +- .../auto-complete/demo/non-case-sensitive.ts | 20 +- components/auto-complete/demo/options.ts | 16 +- .../auto-complete/demo/uncertain-category.ts | 58 +- .../nz-autocomplete-optgroup.component.ts | 19 +- .../nz-autocomplete-option.component.ts | 35 +- .../nz-autocomplete-trigger.directive.ts | 75 +- .../nz-autocomplete.component.ts | 60 +- .../auto-complete/nz-autocomplete.module.ts | 17 +- .../auto-complete/nz-autocomplete.spec.ts | 474 ++++----- components/avatar/avatar.spec.ts | 40 +- components/avatar/demo/badge.ts | 14 +- components/avatar/demo/basic.ts | 40 +- components/avatar/demo/dynamic.ts | 21 +- components/avatar/demo/type.ts | 28 +- components/avatar/nz-avatar.component.ts | 28 +- components/avatar/nz-avatar.module.ts | 9 +- components/back-top/back-top.spec.ts | 41 +- components/back-top/demo/basic.ts | 15 +- components/back-top/demo/custom.ts | 38 +- components/back-top/demo/target.ts | 37 +- components/back-top/nz-back-top.component.ts | 25 +- components/back-top/nz-back-top.module.ts | 11 +- components/badge/demo/basic.ts | 31 +- components/badge/demo/change.ts | 33 +- components/badge/demo/dot.ts | 10 +- components/badge/demo/link.ts | 25 +- components/badge/demo/no-wrapper.ts | 20 +- components/badge/demo/overflow.ts | 31 +- components/badge/demo/status.ts | 19 +- components/badge/nz-badge.component.ts | 28 +- components/badge/nz-badge.module.ts | 9 +- components/badge/nz-badge.spec.ts | 21 +- components/breadcrumb/demo/basic.ts | 8 +- components/breadcrumb/demo/router.ts | 8 +- components/breadcrumb/demo/separator.ts | 9 +- components/breadcrumb/demo/withIcon.ts | 7 +- .../nz-breadcrumb-item.component.ts | 28 +- .../breadcrumb/nz-breadcrumb.component.ts | 66 +- components/breadcrumb/nz-breadcrumb.module.ts | 6 +- components/breadcrumb/nz-breadcrumb.spec.ts | 81 +- components/button/demo/basic.ts | 10 +- components/button/demo/block.ts | 10 +- components/button/demo/button-group.ts | 10 +- components/button/demo/disabled.ts | 14 +- components/button/demo/ghost.ts | 7 +- components/button/demo/icon.ts | 7 +- components/button/demo/loading.ts | 10 +- components/button/demo/multiple.ts | 5 +- components/button/demo/size.ts | 12 +- .../button/nz-button-group.component.ts | 20 +- components/button/nz-button.component.ts | 68 +- components/button/nz-button.module.ts | 9 +- components/button/nz-button.spec.ts | 134 +-- components/calendar/demo/basic.ts | 3 +- components/calendar/demo/card.ts | 8 +- components/calendar/demo/notice-calendar.ts | 48 +- components/calendar/demo/select.ts | 6 +- components/calendar/nz-calendar-cells.ts | 8 +- .../calendar/nz-calendar-header.component.ts | 23 +- .../calendar/nz-calendar-header.spec.ts | 37 +- components/calendar/nz-calendar.component.ts | 138 ++- components/calendar/nz-calendar.module.ts | 13 +- components/calendar/nz-calendar.spec.ts | 44 +- components/card/demo/basic.ts | 13 +- components/card/demo/border-less.ts | 13 +- components/card/demo/flexible-content.ts | 5 +- components/card/demo/grid-card.ts | 2 +- components/card/demo/in-column.ts | 13 +- components/card/demo/inner.ts | 3 +- components/card/demo/loading.ts | 22 +- components/card/demo/meta.ts | 13 +- components/card/demo/simple.ts | 13 +- components/card/demo/tabs.ts | 4 +- components/card/nz-card-loading.component.ts | 20 +- components/card/nz-card-meta.component.ts | 20 +- components/card/nz-card-tab.component.ts | 6 +- components/card/nz-card.component.ts | 38 +- components/card/nz-card.module.ts | 9 +- components/card/nz-card.spec.ts | 12 +- components/carousel/demo/autoplay.ts | 34 +- components/carousel/demo/basic.ts | 34 +- components/carousel/demo/fade.ts | 34 +- components/carousel/demo/vertical.ts | 34 +- .../carousel/nz-carousel-content.directive.ts | 7 +- components/carousel/nz-carousel.component.ts | 64 +- components/carousel/nz-carousel.module.ts | 9 +- components/carousel/nz-carousel.spec.ts | 73 +- components/cascader/demo/basic.ts | 159 +-- .../cascader/demo/change-on-function.ts | 94 +- components/cascader/demo/change-on-select.ts | 87 +- .../cascader/demo/custom-field-names.ts | 94 +- components/cascader/demo/custom-render.ts | 98 +- .../demo/default-value-and-asyn-options.ts | 85 +- .../demo/default-value-and-lazyload.ts | 93 +- components/cascader/demo/default-value.ts | 84 +- components/cascader/demo/disabled.ts | 87 +- components/cascader/demo/hover.ts | 84 +- components/cascader/demo/lazy.ts | 93 +- components/cascader/demo/modal.ts | 93 +- components/cascader/demo/reactive-form.ts | 84 +- components/cascader/demo/search.ts | 157 +-- components/cascader/demo/size.ts | 98 +- components/cascader/demo/trigger-action.ts | 81 +- components/cascader/demo/trigger.ts | 85 +- .../cascader/nz-cascader-li.component.ts | 31 +- components/cascader/nz-cascader.component.ts | 222 ++-- components/cascader/nz-cascader.module.ts | 21 +- components/cascader/nz-cascader.spec.ts | 970 +++++++++++------- components/cascader/types.ts | 4 +- components/checkbox/demo/basic.ts | 4 +- components/checkbox/demo/check-all.ts | 9 +- components/checkbox/demo/controller.ts | 10 +- components/checkbox/demo/disabled.ts | 8 +- components/checkbox/demo/group.ts | 8 +- components/checkbox/demo/layout.ts | 1 - .../checkbox/nz-checkbox-group.component.ts | 19 +- .../checkbox/nz-checkbox-wrapper.component.ts | 8 +- components/checkbox/nz-checkbox.component.ts | 24 +- components/checkbox/nz-checkbox.module.ts | 17 +- components/checkbox/nz-checkbox.spec.ts | 111 +- components/collapse/demo/accordion.ts | 14 +- components/collapse/demo/basic.ts | 28 +- components/collapse/demo/borderless.ts | 22 +- components/collapse/demo/custom.ts | 46 +- components/collapse/demo/mix.ts | 36 +- components/collapse/demo/noarrow.ts | 23 +- .../collapse/nz-collapse-panel.component.ts | 41 +- components/collapse/nz-collapse.component.ts | 39 +- components/collapse/nz-collapse.module.ts | 10 +- components/collapse/nz-collapse.spec.ts | 82 +- components/comment/demo/basic.ts | 47 +- components/comment/demo/editor.ts | 20 +- components/comment/demo/list.ts | 10 +- components/comment/demo/nested.ts | 25 +- components/comment/nz-comment-cells.ts | 32 +- components/comment/nz-comment.component.ts | 19 +- components/comment/nz-comment.module.ts | 12 +- components/comment/nz-comment.spec.ts | 42 +- .../date-picker/abstract-picker.component.ts | 27 +- .../date-picker/date-picker.component.spec.ts | 145 ++- .../date-picker/date-picker.component.ts | 19 +- components/date-picker/date-picker.module.ts | 11 +- .../date-range-picker.component.ts | 28 +- components/date-picker/demo/basic.ts | 33 +- components/date-picker/demo/date-render.ts | 27 +- components/date-picker/demo/disabled-date.ts | 44 +- components/date-picker/demo/disabled.ts | 23 +- components/date-picker/demo/extra-footer.ts | 16 +- components/date-picker/demo/format.ts | 20 +- components/date-picker/demo/mode.ts | 19 +- .../date-picker/demo/presetted-ranges.ts | 30 +- components/date-picker/demo/size.ts | 16 +- components/date-picker/demo/start-end.ts | 21 +- components/date-picker/demo/time.ts | 20 +- .../date-picker/header-picker.component.ts | 12 +- .../month-picker.component.spec.ts | 53 +- .../date-picker/month-picker.component.ts | 29 +- components/date-picker/picker.component.ts | 48 +- .../range-picker.component.spec.ts | 252 +++-- .../date-picker/range-picker.component.ts | 29 +- components/date-picker/standard-types.ts | 2 +- .../date-picker/week-picker.component.spec.ts | 7 +- .../date-picker/week-picker.component.ts | 29 +- .../date-picker/year-picker.component.spec.ts | 56 +- .../date-picker/year-picker.component.ts | 29 +- components/divider/demo/horizontal.ts | 25 +- components/divider/demo/orientation.ts | 15 +- components/divider/demo/vertical.ts | 8 +- components/divider/divider.spec.ts | 33 +- components/divider/nz-divider.component.ts | 23 +- components/divider/nz-divider.module.ts | 9 +- components/drawer/demo/basic-right.ts | 9 +- components/drawer/demo/from-drawer.ts | 46 +- components/drawer/demo/multi-level-drawer.ts | 38 +- components/drawer/demo/placement.ts | 10 +- components/drawer/demo/service.ts | 27 +- components/drawer/demo/user-profile.ts | 84 +- components/drawer/nz-drawer-options.ts | 2 +- components/drawer/nz-drawer-ref.ts | 1 - components/drawer/nz-drawer.component.ts | 19 +- components/drawer/nz-drawer.module.ts | 13 +- components/drawer/nz-drawer.service.ts | 17 +- components/drawer/nz-drawer.spec.ts | 184 +++- components/dropdown/demo/basic.ts | 12 +- components/dropdown/demo/context-menu.ts | 11 +- components/dropdown/demo/dropdown-button.ts | 4 +- components/dropdown/demo/event.ts | 9 +- components/dropdown/demo/item.ts | 12 +- components/dropdown/demo/overlay-visible.ts | 9 +- components/dropdown/demo/placement.ts | 10 +- components/dropdown/demo/sub-menu.ts | 9 +- components/dropdown/demo/trigger.ts | 12 +- .../dropdown/nz-dropdown-button.component.ts | 56 +- .../dropdown/nz-dropdown-context.component.ts | 30 +- components/dropdown/nz-dropdown.component.ts | 75 +- components/dropdown/nz-dropdown.directive.ts | 5 +- components/dropdown/nz-dropdown.module.ts | 17 +- components/dropdown/nz-dropdown.service.ts | 45 +- components/dropdown/nz-dropdown.spec.ts | 92 +- components/empty/demo/basic.ts | 8 +- components/empty/demo/config.ts | 25 +- components/empty/demo/customize.ts | 16 +- components/empty/nz-embed-empty.component.ts | 16 +- components/empty/nz-empty-config.ts | 6 +- components/empty/nz-empty-error.ts | 3 +- components/empty/nz-empty.component.ts | 32 +- components/empty/nz-empty.module.ts | 9 +- components/empty/nz-empty.service.ts | 14 +- components/empty/nz-empty.spec.ts | 43 +- components/form/demo/advanced-search.ts | 26 +- components/form/demo/coordinated.ts | 44 +- components/form/demo/dynamic-form-item.ts | 67 +- components/form/demo/dynamic-rule.ts | 39 +- components/form/demo/horizontal-login.ts | 33 +- components/form/demo/layout.ts | 59 +- components/form/demo/normal-login.ts | 54 +- components/form/demo/register.ts | 99 +- components/form/demo/time-related-controls.ts | 33 +- components/form/demo/validate-reactive.ts | 87 +- components/form/demo/validate-static.ts | 22 +- components/form/nz-form-control.component.ts | 67 +- components/form/nz-form-control.spec.ts | 75 +- components/form/nz-form-explain.component.ts | 20 +- components/form/nz-form-extra.component.ts | 12 +- components/form/nz-form-item.component.ts | 30 +- components/form/nz-form-item.spec.ts | 7 +- components/form/nz-form-label.component.ts | 24 +- components/form/nz-form-label.spec.ts | 7 +- components/form/nz-form-split.component.ts | 8 +- components/form/nz-form-split.spec.ts | 11 +- components/form/nz-form-text.component.ts | 8 +- components/form/nz-form-text.spec.ts | 11 +- components/form/nz-form.directive.ts | 12 +- components/form/nz-form.module.ts | 10 +- components/form/nz-form.spec.ts | 7 +- components/grid/demo/basic.ts | 6 +- components/grid/demo/flex-align.ts | 8 +- components/grid/demo/flex-order.ts | 8 +- components/grid/demo/flex.ts | 6 +- components/grid/demo/gutter.ts | 7 +- components/grid/demo/offset.ts | 5 +- components/grid/demo/playground.ts | 36 +- components/grid/demo/responsive-more.ts | 8 +- components/grid/demo/responsive.ts | 8 +- components/grid/demo/sort.ts | 5 +- components/grid/nz-col.directive.ts | 67 +- components/grid/nz-grid.module.ts | 9 +- components/grid/nz-grid.spec.ts | 168 +-- components/grid/nz-row.directive.ts | 45 +- components/i18n/date-helper.service.spec.ts | 19 +- components/i18n/date-helper.service.ts | 33 +- components/i18n/nz-i18n.module.ts | 15 +- components/i18n/nz-i18n.pipe.ts | 3 +- components/i18n/nz-i18n.service.spec.ts | 1 - components/i18n/nz-i18n.service.ts | 15 +- components/icon/demo/basic.ts | 17 +- components/icon/demo/custom.ts | 69 +- components/icon/demo/iconfont.ts | 16 +- components/icon/demo/namespace.ts | 17 +- components/icon/demo/twotone.ts | 17 +- components/icon/nz-icon-test.module.ts | 4 +- components/icon/nz-icon.directive.ts | 45 +- components/icon/nz-icon.module.ts | 7 +- components/icon/nz-icon.spec.ts | 115 +-- components/input-number/demo/digit.ts | 10 +- components/input-number/demo/disabled.ts | 11 +- components/input-number/demo/formatter.ts | 22 +- components/input-number/demo/size.ts | 7 +- .../input-number/nz-input-number.component.ts | 51 +- .../input-number/nz-input-number.module.ts | 9 +- .../input-number/nz-input-number.spec.ts | 31 +- components/input/demo/addon.ts | 8 +- components/input/demo/autosize-textarea.ts | 8 +- components/input/demo/basic.ts | 8 +- components/input/demo/group.ts | 114 +- components/input/demo/password-input.ts | 13 +- components/input/demo/presuffix.ts | 10 +- components/input/demo/search-input.ts | 17 +- components/input/demo/size.ts | 13 +- components/input/demo/tooltip.ts | 27 +- components/input/nz-autosize.directive.ts | 66 +- components/input/nz-autosize.spec.ts | 57 +- components/input/nz-input-group.component.ts | 43 +- components/input/nz-input-group.spec.ts | 40 +- components/input/nz-input.directive.ts | 13 +- components/input/nz-input.module.ts | 3 +- components/input/nz-input.spec.ts | 21 +- components/layout/demo/basic.ts | 64 +- components/layout/demo/custom-trigger.ts | 22 +- components/layout/demo/fixed-sider.ts | 75 +- components/layout/demo/fixed.ts | 23 +- components/layout/demo/responsive.ts | 30 +- components/layout/demo/side.ts | 13 +- components/layout/demo/top-side-2.ts | 20 +- components/layout/demo/top-side.ts | 20 +- components/layout/demo/top.ts | 19 +- components/layout/nz-content.component.ts | 18 +- components/layout/nz-footer.component.ts | 18 +- components/layout/nz-header.component.ts | 18 +- components/layout/nz-layout.component.ts | 9 +- components/layout/nz-layout.module.ts | 9 +- components/layout/nz-layout.spec.ts | 104 +- components/layout/nz-sider.component.ts | 59 +- components/list/demo/basic.ts | 31 +- components/list/demo/grid.ts | 32 +- components/list/demo/infinite-load.ts | 42 +- components/list/demo/loadmore.ts | 89 +- components/list/demo/resposive.ts | 25 +- components/list/demo/simple.ts | 44 +- components/list/demo/vertical.ts | 63 +- components/list/interface.ts | 18 +- components/list/list.spec.ts | 154 ++- .../list/nz-list-item-meta.component.ts | 9 +- components/list/nz-list-item.component.ts | 13 +- components/list/nz-list.component.ts | 45 +- components/list/nz-list.module.ts | 24 +- components/mention/demo/async.ts | 22 +- components/mention/demo/avatar.ts | 36 +- components/mention/demo/basic.ts | 26 +- components/mention/demo/controlled.ts | 75 +- components/mention/demo/custom-tag.ts | 26 +- components/mention/demo/multilines.ts | 18 +- components/mention/demo/multiple-trigger.ts | 27 +- components/mention/demo/placement.ts | 19 +- components/mention/demo/preview.ts | 34 +- components/mention/demo/readonly.ts | 33 +- components/mention/nz-mention-suggestions.ts | 2 +- components/mention/nz-mention-trigger.ts | 18 +- components/mention/nz-mention.component.ts | 118 +-- components/mention/nz-mention.module.ts | 9 +- components/mention/nz-mention.spec.ts | 184 ++-- components/menu/demo/horizontal.ts | 6 +- components/menu/demo/inline-collapsed.ts | 4 +- components/menu/demo/inline.ts | 5 +- components/menu/demo/recursive.ts | 124 ++- components/menu/demo/sider-current.ts | 9 +- components/menu/demo/switch-mode.ts | 17 +- components/menu/demo/theme.ts | 11 +- components/menu/demo/vertical.ts | 5 +- components/menu/nz-menu-group.component.ts | 8 +- components/menu/nz-menu-item.directive.ts | 62 +- components/menu/nz-menu.directive.ts | 42 +- components/menu/nz-menu.module.ts | 15 +- components/menu/nz-menu.spec.ts | 149 +-- components/menu/nz-submenu.component.ts | 136 +-- components/menu/nz-submenu.service.ts | 14 +- components/message/demo/close.ts | 20 +- components/message/demo/duration.ts | 11 +- components/message/demo/info.ts | 6 +- components/message/demo/loading.ts | 6 +- components/message/demo/other.ts | 7 +- components/message/nz-message-config.ts | 10 +- .../message/nz-message-container.component.ts | 25 +- components/message/nz-message.component.ts | 16 +- components/message/nz-message.module.ts | 11 +- components/message/nz-message.service.ts | 26 +- components/message/nz-message.spec.ts | 31 +- components/modal/css-unit.pipe.ts | 1 - components/modal/demo/async.ts | 8 +- components/modal/demo/confirm-promise.ts | 11 +- components/modal/demo/confirm.ts | 29 +- components/modal/demo/footer.ts | 11 +- components/modal/demo/info.ts | 12 +- components/modal/demo/locale.ts | 4 +- components/modal/demo/manual.ts | 2 +- components/modal/demo/position.ts | 42 +- components/modal/demo/service.ts | 59 +- components/modal/nz-modal-control.service.ts | 5 +- components/modal/nz-modal-ref.class.ts | 3 +- components/modal/nz-modal.component.ts | 119 ++- components/modal/nz-modal.module.ts | 13 +- components/modal/nz-modal.service.ts | 31 +- components/modal/nz-modal.spec.ts | 220 ++-- components/modal/nz-modal.type.ts | 15 +- components/notification/demo/basic.ts | 11 +- components/notification/demo/custom-icon.ts | 17 +- components/notification/demo/custom-style.ts | 24 +- components/notification/demo/duration.ts | 11 +- components/notification/demo/placement.ts | 16 +- components/notification/demo/template.ts | 13 +- components/notification/demo/update.ts | 15 +- components/notification/demo/with-btn.ts | 17 +- components/notification/demo/with-icon.ts | 12 +- .../notification/nz-notification-config.ts | 18 +- .../nz-notification-container.component.ts | 34 +- .../notification/nz-notification.component.ts | 10 +- .../notification/nz-notification.module.ts | 11 +- .../notification/nz-notification.service.ts | 21 +- .../notification/nz-notification.spec.ts | 30 +- components/pagination/demo/basic.ts | 8 +- components/pagination/demo/changer.ts | 8 +- components/pagination/demo/controlled.ts | 7 +- components/pagination/demo/itemRender.ts | 11 +- components/pagination/demo/jump.ts | 8 +- components/pagination/demo/mini.ts | 23 +- components/pagination/demo/more.ts | 8 +- components/pagination/demo/simple.ts | 8 +- components/pagination/demo/total.ts | 13 +- .../pagination/nz-pagination.component.ts | 26 +- components/pagination/nz-pagination.module.ts | 10 +- components/pagination/nz-pagination.spec.ts | 50 +- components/polyfills.ts | 14 +- components/popconfirm/demo/basic.ts | 10 +- components/popconfirm/demo/custom-icon.ts | 4 +- components/popconfirm/demo/dynamic-trigger.ts | 19 +- components/popconfirm/demo/locale.ts | 16 +- components/popconfirm/demo/placement.ts | 157 ++- .../popconfirm/nz-popconfirm.component.ts | 22 +- .../popconfirm/nz-popconfirm.directive.ts | 13 +- components/popconfirm/nz-popconfirm.module.ts | 12 +- components/popconfirm/nz-popconfirm.spec.ts | 93 +- .../popover/demo/arrow-point-at-center.ts | 23 +- components/popover/demo/basic.ts | 14 +- components/popover/demo/control.ts | 5 +- components/popover/demo/placement.ts | 24 +- components/popover/demo/template.ts | 13 +- components/popover/demo/triggerType.ts | 7 +- components/popover/nz-popover.component.ts | 27 +- components/popover/nz-popover.module.ts | 12 +- components/popover/nz-popover.spec.ts | 18 +- components/progress/demo/circle-dynamic.ts | 1 - components/progress/demo/circle-mini.ts | 4 +- components/progress/demo/circle.ts | 7 +- components/progress/demo/dashboard.ts | 2 +- components/progress/demo/format.ts | 4 +- components/progress/demo/line-mini.ts | 3 +- components/progress/demo/line.ts | 2 +- components/progress/demo/segment.ts | 2 +- components/progress/nz-progress.component.ts | 34 +- components/progress/nz-progress.module.ts | 9 +- components/progress/nz-progress.spec.ts | 91 +- components/radio/demo/basic.ts | 3 +- components/radio/demo/disable.ts | 4 +- components/radio/demo/radiogroup-more.ts | 11 +- components/radio/demo/radiogroup-options.ts | 8 +- components/radio/nz-radio-button.component.ts | 20 +- components/radio/nz-radio-group.component.ts | 65 +- components/radio/nz-radio.component.ts | 25 +- components/radio/nz-radio.module.ts | 9 +- components/radio/nz-radio.spec.ts | 89 +- components/rate/demo/basic.ts | 7 +- components/rate/demo/character.ts | 11 +- components/rate/demo/clear.ts | 2 +- components/rate/demo/disabled.ts | 8 +- components/rate/demo/half.ts | 7 +- components/rate/demo/text.ts | 4 +- components/rate/nz-rate-item.component.ts | 12 +- components/rate/nz-rate.component.ts | 42 +- components/rate/nz-rate.module.ts | 9 +- components/rate/nz-rate.spec.ts | 43 +- .../select/demo/automatic-tokenization.ts | 7 +- components/select/demo/basic.ts | 2 +- components/select/demo/coordinate.ts | 12 +- .../select/demo/custom-dropdown-menu.ts | 7 +- components/select/demo/hide-selected.ts | 9 +- components/select/demo/label-in-value.ts | 22 +- components/select/demo/multiple.ts | 19 +- components/select/demo/scroll-load.ts | 36 +- components/select/demo/search-box.ts | 31 +- components/select/demo/search.ts | 8 +- components/select/demo/select-users.ts | 43 +- components/select/demo/size.ts | 24 +- components/select/demo/tags.ts | 7 +- .../select/nz-option-container.component.ts | 45 +- components/select/nz-option-container.spec.ts | 46 +- .../select/nz-option-group.component.ts | 6 +- components/select/nz-option-li.component.ts | 43 +- components/select/nz-option-li.spec.ts | 19 +- components/select/nz-option.component.ts | 6 +- components/select/nz-option.pipe.spec.ts | 12 +- components/select/nz-option.pipe.ts | 14 +- .../select/nz-select-top-control.component.ts | 41 +- .../select/nz-select-top-control.spec.ts | 42 +- .../nz-select-unselectable.directive.ts | 6 +- .../select/nz-select-unselectable.spec.ts | 10 +- components/select/nz-select.component.spec.ts | 43 +- components/select/nz-select.component.ts | 128 +-- components/select/nz-select.module.ts | 7 +- components/select/nz-select.service.spec.ts | 34 +- components/select/nz-select.service.ts | 105 +- components/skeleton/demo/active.ts | 2 +- components/skeleton/demo/basic.ts | 2 +- components/skeleton/demo/children.ts | 7 +- components/skeleton/demo/complex.ts | 2 +- components/skeleton/demo/list.ts | 20 +- components/skeleton/nz-skeleton.component.ts | 19 +- components/skeleton/nz-skeleton.module.ts | 6 +- components/skeleton/nz-skeleton.spec.ts | 9 +- components/slider/demo/basic.ts | 2 +- components/slider/demo/event.ts | 17 +- components/slider/demo/icon-slider.ts | 8 +- components/slider/demo/input-number.ts | 19 +- components/slider/demo/mark.ts | 32 +- components/slider/demo/tooltip.ts | 3 +- components/slider/demo/vertical.ts | 16 +- components/slider/nz-slider-definitions.ts | 2 +- components/slider/nz-slider-error.ts | 4 +- .../slider/nz-slider-handle.component.ts | 22 +- .../slider/nz-slider-marks.component.ts | 16 +- components/slider/nz-slider-step.component.ts | 12 +- .../slider/nz-slider-track.component.ts | 8 +- components/slider/nz-slider.component.ts | 92 +- components/slider/nz-slider.module.ts | 4 +- components/slider/nz-slider.spec.ts | 118 ++- components/spin/demo/basic.ts | 6 +- components/spin/demo/custom-indicator.ts | 10 +- components/spin/demo/delayAndDebounce.ts | 6 +- components/spin/demo/inside.ts | 6 +- components/spin/demo/nested.ts | 6 +- components/spin/demo/size.ts | 10 +- components/spin/demo/tip.ts | 11 +- components/spin/nz-spin.component.ts | 26 +- components/spin/nz-spin.module.ts | 9 +- components/spin/nz-spin.spec.ts | 13 +- components/statistic/demo/basic.ts | 5 +- components/statistic/demo/card.ts | 9 +- components/statistic/demo/unit.ts | 3 +- .../statistic/nz-countdown.component.ts | 6 +- components/statistic/nz-countdown.spec.ts | 10 +- .../nz-statistic-number.component.ts | 21 +- .../statistic/nz-statistic-number.spec.ts | 6 +- .../statistic/nz-statistic.component.ts | 18 +- components/statistic/nz-statistic.module.ts | 9 +- components/statistic/nz-statistic.spec.ts | 11 +- components/statistic/nz-time-range.pipe.ts | 11 +- components/statistic/nz-time-range.spec.ts | 10 +- .../steps/demo/customized-progress-dot.ts | 5 +- components/steps/demo/error.ts | 3 +- components/steps/demo/icon.ts | 3 +- components/steps/demo/progress-dot.ts | 3 +- components/steps/demo/simple.ts | 3 +- components/steps/demo/step-next.ts | 7 +- components/steps/demo/vertical-small.ts | 3 +- components/steps/demo/vertical.ts | 3 +- components/steps/nz-step.component.ts | 31 +- components/steps/nz-steps.component.ts | 23 +- components/steps/nz-steps.module.ts | 9 +- components/steps/nz-steps.spec.ts | 242 +++-- components/switch/demo/basic.ts | 4 +- components/switch/demo/control.ts | 5 +- components/switch/demo/disabled.ts | 15 +- components/switch/demo/loading.ts | 15 +- components/switch/demo/size.ts | 15 +- components/switch/demo/text.ts | 23 +- components/switch/nz-switch.component.ts | 29 +- components/switch/nz-switch.module.ts | 9 +- components/switch/nz-switch.spec.ts | 30 +- components/table/demo/ajax.ts | 59 +- components/table/demo/basic.ts | 26 +- components/table/demo/bordered.ts | 30 +- components/table/demo/colspan-rowspan.ts | 71 +- components/table/demo/custom-filter-panel.ts | 103 +- components/table/demo/default-filter.ts | 74 +- components/table/demo/drag-sorting.ts | 27 +- components/table/demo/dynamic-settings.ts | 65 +- components/table/demo/edit-cell.ts | 31 +- components/table/demo/edit-row.ts | 36 +- components/table/demo/expand-children.ts | 124 +-- components/table/demo/expand.ts | 45 +- components/table/demo/fixed-columns-header.ts | 29 +- components/table/demo/fixed-columns.ts | 37 +- components/table/demo/fixed-header.ts | 15 +- components/table/demo/grouping-columns.ts | 55 +- components/table/demo/head.ts | 73 +- components/table/demo/nested-table.ts | 86 +- components/table/demo/reset-filter.ts | 108 +- .../table/demo/row-selection-and-operation.ts | 69 +- components/table/demo/row-selection-custom.ts | 53 +- components/table/demo/size.ts | 54 +- components/table/demo/template.ts | 3 +- components/table/demo/virtual.ts | 30 +- components/table/nz-table.component.ts | 93 +- components/table/nz-table.module.ts | 25 +- components/table/nz-table.spec.ts | 189 ++-- components/table/nz-tbody.directive.ts | 6 +- components/table/nz-tbody.spec.ts | 15 +- components/table/nz-td.component.ts | 27 +- components/table/nz-td.spec.ts | 61 +- components/table/nz-th.component.ts | 47 +- components/table/nz-th.spec.ts | 168 +-- components/table/nz-thead.component.ts | 45 +- components/table/nz-thead.spec.ts | 14 +- components/table/nz-tr.directive.ts | 12 +- components/table/nz-tr.spec.ts | 12 +- .../table/nz-virtual-scroll.directive.ts | 4 +- components/tabs/demo/basic.ts | 6 +- components/tabs/demo/card-top.ts | 8 +- components/tabs/demo/card.ts | 11 +- components/tabs/demo/custom-add-trigger.ts | 7 +- components/tabs/demo/disabled.ts | 14 +- components/tabs/demo/editable-card.ts | 2 +- components/tabs/demo/extra.ts | 6 +- components/tabs/demo/icon.ts | 15 +- components/tabs/demo/lazy.ts | 14 +- components/tabs/demo/position.ts | 17 +- components/tabs/demo/size.ts | 11 +- components/tabs/demo/slide.ts | 17 +- components/tabs/nz-tab-body.component.ts | 12 +- components/tabs/nz-tab-label.directive.ts | 2 +- components/tabs/nz-tab.component.ts | 18 +- components/tabs/nz-tab.directive.ts | 7 +- components/tabs/nz-tabs-ink-bar.directive.ts | 29 +- components/tabs/nz-tabs-nav.component.ts | 60 +- components/tabs/nz-tabs-nav.spec.ts | 53 +- components/tabs/nz-tabs.module.ts | 25 +- components/tabs/nz-tabs.spec.ts | 206 ++-- components/tabs/nz-tabset.component.ts | 92 +- components/tag/demo/basic.ts | 3 +- components/tag/demo/colorful.ts | 19 +- components/tag/demo/control.ts | 34 +- components/tag/demo/hot-tags.ts | 13 +- components/tag/nz-tag.component.ts | 43 +- components/tag/nz-tag.module.ts | 13 +- components/tag/nz-tag.spec.ts | 7 +- components/time-picker/demo/disabled-part.ts | 14 +- components/time-picker/demo/disabled.ts | 3 +- .../time-picker/demo/interval-options.ts | 3 +- components/time-picker/demo/size.ts | 10 +- .../nz-time-picker-panel.component.spec.ts | 102 +- .../nz-time-picker-panel.component.ts | 101 +- .../nz-time-picker.component.spec.ts | 23 +- .../time-picker/nz-time-picker.component.ts | 46 +- .../time-picker/nz-time-picker.module.ts | 16 +- .../nz-time-value-accessor.directive.spec.ts | 8 +- .../nz-time-value-accessor.directive.ts | 11 +- components/time-picker/time-holder.spec.ts | 16 +- components/time-picker/time-holder.ts | 4 +- components/timeline/demo/alternate.ts | 9 +- components/timeline/demo/basic.ts | 6 +- components/timeline/demo/color.ts | 8 +- components/timeline/demo/custom.ts | 4 +- components/timeline/demo/pending.ts | 1 - components/timeline/demo/right.ts | 3 +- .../timeline/nz-timeline-item.component.ts | 13 +- components/timeline/nz-timeline.component.ts | 25 +- components/timeline/nz-timeline.module.ts | 9 +- components/timeline/nz-timeline.spec.ts | 75 +- .../tooltip/demo/arrow-point-at-center.ts | 19 +- components/tooltip/demo/basic.ts | 7 +- components/tooltip/demo/placement.ts | 7 +- components/tooltip/demo/template.ts | 3 +- components/tooltip/nz-tooltip.component.ts | 39 +- components/tooltip/nz-tooltip.directive.ts | 32 +- components/tooltip/nz-tooltip.module.ts | 11 +- components/tooltip/nz-tooltip.spec.ts | 26 +- components/transfer/demo/advanced.ts | 26 +- components/transfer/demo/basic.ts | 18 +- components/transfer/demo/can-move.ts | 15 +- components/transfer/demo/custom-item.ts | 24 +- components/transfer/demo/search.ts | 12 +- .../transfer/nz-transfer-list.component.ts | 27 +- .../transfer/nz-transfer-search.component.ts | 23 +- components/transfer/nz-transfer.component.ts | 41 +- components/transfer/nz-transfer.module.ts | 18 +- components/transfer/transfer.spec.ts | 182 ++-- components/tree-select/demo/async.ts | 66 +- components/tree-select/demo/basic.ts | 44 +- components/tree-select/demo/checkable.ts | 84 +- components/tree-select/demo/multiple.ts | 50 +- .../tree-select/nz-tree-select.component.ts | 108 +- .../tree-select/nz-tree-select.module.ts | 18 +- .../tree-select/nz-tree-select.service.ts | 4 +- components/tree-select/nz-tree-select.spec.ts | 157 ++- components/tree/demo/basic-controlled.ts | 87 +- components/tree/demo/basic.ts | 58 +- components/tree/demo/customized-icon.ts | 15 +- components/tree/demo/directory.ts | 136 +-- components/tree/demo/draggable-confirm.ts | 44 +- components/tree/demo/draggable.ts | 124 +-- components/tree/demo/dynamic.ts | 14 +- components/tree/demo/line.ts | 61 +- components/tree/demo/search.ts | 96 +- components/tree/nz-tree-base.service.ts | 45 +- components/tree/nz-tree-node.component.ts | 135 +-- components/tree/nz-tree-node.ts | 85 +- components/tree/nz-tree-util.ts | 2 +- components/tree/nz-tree.component.ts | 133 ++- components/tree/nz-tree.module.ts | 22 +- components/tree/nz-tree.service.ts | 4 +- components/tree/nz-tree.spec.ts | 552 +++++----- components/upload/demo/avatar.ts | 58 +- components/upload/demo/basic.ts | 9 +- components/upload/demo/custom-request.ts | 99 +- components/upload/demo/directory.ts | 10 +- components/upload/demo/drag.ts | 29 +- components/upload/demo/file-list.ts | 10 +- components/upload/demo/filter.ts | 24 +- components/upload/demo/manually.ts | 23 +- components/upload/demo/picture-card.ts | 58 +- components/upload/demo/picture-style.ts | 51 +- components/upload/interface.ts | 2 +- components/upload/nz-upload-btn.component.ts | 175 ++-- components/upload/nz-upload-list.component.ts | 39 +- components/upload/nz-upload.component.ts | 109 +- components/upload/nz-upload.module.ts | 6 +- components/upload/upload.spec.ts | 504 ++++----- package.json | 50 +- schematics/ng-add/index.ts | 5 +- schematics/ng-add/schema.ts | 42 +- schematics/ng-update/index.ts | 10 +- schematics/utils/package-config.ts | 13 +- scripts/schematics/template/index.ts | 13 +- .../_site/doc/app/_demo/demo.component.ts | 4 +- scripts/site/_site/doc/app/app.component.ts | 88 +- scripts/site/_site/doc/app/app.module.ts | 15 +- .../site/_site/doc/app/app.routing.module.ts | 2 +- .../share/nz-codebox/nz-codebox.component.ts | 137 ++- .../app/share/nz-codebox/nz-codebox.module.ts | 11 +- .../nz-highlight/nz-highlight.component.ts | 6 +- .../share/nz-highlight/nz-highlight.module.ts | 10 +- .../nz-nav-bottom/nz-nav-bottom.component.ts | 30 +- .../nz-nav-bottom/nz-nav-bottom.module.ts | 10 +- .../site/_site/doc/app/share/share.module.ts | 7 +- scripts/site/_site/doc/main.ts | 5 +- scripts/site/_site/doc/polyfills.ts | 5 +- .../site/_site/iframe/app/app.component.ts | 5 +- scripts/site/_site/iframe/main.ts | 5 +- scripts/site/_site/iframe/polyfills.ts | 5 +- tslint.json | 159 +-- 746 files changed, 14088 insertions(+), 11814 deletions(-) create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000000..28d9a3ca443 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +**/*.md +**/*.svg +**/*.html +**/test.ts +**/*.less +coverage/ +publish/ +site/ +package.json +**/template/* \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000000..76e058ebaaf --- /dev/null +++ b/.prettierrc @@ -0,0 +1,14 @@ +{ + "singleQuote": true, + "printWidth": 120, + "tabWidth": 2, + "useTabs": false, + "overrides": [ + { + "files": ".prettierrc", + "options": { + "parser": "json" + } + } + ] +} diff --git a/components/affix/affix.spec.ts b/components/affix/affix.spec.ts index c6af8e00465..5492c4fecea 100644 --- a/components/affix/affix.spec.ts +++ b/components/affix/affix.spec.ts @@ -1,11 +1,5 @@ import { Component, DebugElement, ViewChild } from '@angular/core'; -import { - discardPeriodicTasks, - fakeAsync, - tick, - ComponentFixture, - TestBed -} from '@angular/core/testing'; +import { discardPeriodicTasks, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NzScrollService } from '../core/scroll/nz-scroll.service'; @@ -373,8 +367,8 @@ describe('affix', () => { constructor() { spyOn(component, 'getOffset').and.callFake(this.getOffset.bind(this)); spyOn(scrollService, 'getScroll').and.callFake(this.getScroll.bind(this)); - this.offsets = { 'undefined': { top: 10, left: 0, height: 0, width: 0 } }; - this.scrolls = { 'undefined': { top: 10, left: 0 } }; + this.offsets = { undefined: { top: 10, left: 0, height: 0, width: 0 } }; + this.scrolls = { undefined: { top: 10, left: 0 } }; } getScroll(el?: Element | Window, top: boolean = true): number { @@ -392,7 +386,7 @@ describe('affix', () => { emitScroll(el: Element | Window, top: number, left: number = 0): void { this.scrolls[this.getKey(el)] = { top, left }; - this.emitEvent((el || window), scrollEvent); + this.emitEvent(el || window, scrollEvent); } offsetTo(el: Element, offset: Offset): void { @@ -405,15 +399,12 @@ describe('affix', () => { } offsetYTo(el: Element, offsetTop: number): void { - this.offsetTo( - el, - { - top: offsetTop, - left: 0, - height, - width - } - ); + this.offsetTo(el, { + top: offsetTop, + left: 0, + height, + width + }); } content(): HTMLElement { @@ -476,7 +467,10 @@ describe('affix-extra', () => { dl = fixture.debugElement; }); it('#getOffset', () => { - const ret = fixture.componentInstance.nzAffixComponent.getOffset(fixture.debugElement.query(By.css('#affix')).nativeElement, window); + const ret = fixture.componentInstance.nzAffixComponent.getOffset( + fixture.debugElement.query(By.css('#affix')).nativeElement, + window + ); expect(ret).not.toBeUndefined(); }); it('with window when scrolled below the bottom offset', fakeAsync(() => { @@ -504,13 +498,10 @@ describe('affix-extra', () => { @Component({ template: ` - - - -
+ + + +
` }) class TestAffixComponent { diff --git a/components/affix/demo/basic.ts b/components/affix/demo/basic.ts index 24076c753bc..8719dd040d7 100644 --- a/components/affix/demo/basic.ts +++ b/components/affix/demo/basic.ts @@ -1,20 +1,19 @@ import { Component } from '@angular/core'; @Component({ - selector : 'nz-demo-affix-basic', - template : ` - - - -
- - - + selector: 'nz-demo-affix-basic', + template: ` + + + +
+ + + ` }) -export class NzDemoAffixBasicComponent { -} +export class NzDemoAffixBasicComponent {} diff --git a/components/affix/demo/on-change.ts b/components/affix/demo/on-change.ts index 8ca3ad7d5c1..95d245fb965 100644 --- a/components/affix/demo/on-change.ts +++ b/components/affix/demo/on-change.ts @@ -3,11 +3,11 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-affix-on-change', template: ` - - - + + ` }) export class NzDemoAffixOnChangeComponent { diff --git a/components/affix/demo/target.ts b/components/affix/demo/target.ts index a4c9ff08378..6991b05079e 100644 --- a/components/affix/demo/target.ts +++ b/components/affix/demo/target.ts @@ -3,27 +3,29 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-affix-target', template: ` -
-
- - - + + +
- `, - styles: [` - .scrollable-container { - height: 100px; - overflow-y: scroll; - } + styles: [ + ` + .scrollable-container { + height: 100px; + overflow-y: scroll; + } - .background { - padding-top: 60px; - height: 300px; - background-image: url(//zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg); - } - `] + .background { + padding-top: 60px; + height: 300px; + background-image: url(//zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg); + } + ` + ] }) -export class NzDemoAffixTargetComponent { } +export class NzDemoAffixTargetComponent {} diff --git a/components/affix/nz-affix.component.ts b/components/affix/nz-affix.component.ts index 48d1c580076..ed0f3efaa38 100644 --- a/components/affix/nz-affix.component.ts +++ b/components/affix/nz-affix.component.ts @@ -20,18 +20,19 @@ import { toNumber } from '../core/util/convert'; import { throttleByAnimationFrameDecorator } from '../core/util/throttleByAnimationFrame'; @Component({ - selector : 'nz-affix', - templateUrl : './nz-affix.component.html', + selector: 'nz-affix', + templateUrl: './nz-affix.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - styles : [ ` - nz-affix { - display: block; - } - ` ], - encapsulation : ViewEncapsulation.None + styles: [ + ` + nz-affix { + display: block; + } + ` + ], + encapsulation: ViewEncapsulation.None }) export class NzAffixComponent implements OnInit, OnDestroy { - @Input() set nzTarget(value: string | Element | Window) { this.clearEventListeners(); @@ -65,15 +66,7 @@ export class NzAffixComponent implements OnInit, OnDestroy { @Output() readonly nzChange = new EventEmitter(); private timeout: number; - private readonly events = [ - 'resize', - 'scroll', - 'touchstart', - 'touchmove', - 'touchend', - 'pageshow', - 'load' - ]; + private readonly events = ['resize', 'scroll', 'touchstart', 'touchmove', 'touchend', 'pageshow', 'load']; @ViewChild('fixedEl') private fixedEl: ElementRef; private readonly placeholderNode: HTMLElement; @@ -103,7 +96,10 @@ export class NzAffixComponent implements OnInit, OnDestroy { (this.updatePosition as any).cancel(); } - getOffset(element: Element, target: Element | Window | undefined): { + getOffset( + element: Element, + target: Element | Window | undefined + ): { top: number; left: number; width: number; @@ -120,9 +116,9 @@ export class NzAffixComponent implements OnInit, OnDestroy { const clientLeft = docElem.clientLeft || 0; return { - top : elemRect.top - targetRect.top + scrollTop - clientTop, - left : elemRect.left - targetRect.left + scrollLeft - clientLeft, - width : elemRect.width, + top: elemRect.top - targetRect.top + scrollTop - clientTop, + left: elemRect.left - targetRect.left + scrollLeft - clientLeft, + width: elemRect.width, height: elemRect.height }; } @@ -141,19 +137,21 @@ export class NzAffixComponent implements OnInit, OnDestroy { } private getTargetRect(target: Element | Window | undefined): ClientRect { - return target !== window ? - (target as HTMLElement).getBoundingClientRect() : - { top: 0, left: 0, bottom: 0 } as ClientRect; + return target !== window + ? (target as HTMLElement).getBoundingClientRect() + : ({ top: 0, left: 0, bottom: 0 } as ClientRect); } private genStyle(affixStyle?: NGStyleInterface): string { if (!affixStyle) { return ''; } - return Object.keys(affixStyle).map(key => { - const val = affixStyle[ key ]; - return `${key}:${typeof val === 'string' ? val : val + 'px'}`; - }).join(';'); + return Object.keys(affixStyle) + .map(key => { + const val = affixStyle[key]; + return `${key}:${typeof val === 'string' ? val : val + 'px'}`; + }) + .join(';'); } private setAffixStyle(e: Event, affixStyle?: NGStyleInterface): void { @@ -213,11 +211,11 @@ export class NzAffixComponent implements OnInit, OnDestroy { const elemOffset = this.getOffset(this.placeholderNode, targetNode); const fixedNode = this.fixedEl.nativeElement as HTMLElement; const elemSize = { - width : fixedNode.offsetWidth, + width: fixedNode.offsetWidth, height: fixedNode.offsetHeight }; const offsetMode = { - top : false, + top: false, bottom: false }; // Default to `offsetTop=0`. @@ -229,15 +227,14 @@ export class NzAffixComponent implements OnInit, OnDestroy { offsetMode.bottom = typeof this._offsetBottom === 'number'; } const targetRect = this.getTargetRect(targetNode); - const targetInnerHeight = - (targetNode as Window).innerHeight || (targetNode as HTMLElement).clientHeight; + const targetInnerHeight = (targetNode as Window).innerHeight || (targetNode as HTMLElement).clientHeight; if (scrollTop >= elemOffset.top - (offsetTop as number) && offsetMode.top) { const width = elemOffset.width; const top = targetRect.top + (offsetTop as number); this.setAffixStyle(e, { - position : 'fixed', + position: 'fixed', top, - left : targetRect.left + elemOffset.left, + left: targetRect.left + elemOffset.left, maxHeight: `calc(100vh - ${top}px)`, width }); @@ -249,12 +246,12 @@ export class NzAffixComponent implements OnInit, OnDestroy { scrollTop <= elemOffset.top + elemSize.height + (this._offsetBottom as number) - targetInnerHeight && offsetMode.bottom ) { - const targetBottomOffet = targetNode === window ? 0 : (window.innerHeight - targetRect.bottom); + const targetBottomOffet = targetNode === window ? 0 : window.innerHeight - targetRect.bottom; const width = elemOffset.width; this.setAffixStyle(e, { position: 'fixed', - bottom : targetBottomOffet + (this._offsetBottom as number), - left : targetRect.left + elemOffset.left, + bottom: targetBottomOffet + (this._offsetBottom as number), + left: targetRect.left + elemOffset.left, width }); this.setPlaceholderStyle({ @@ -262,7 +259,12 @@ export class NzAffixComponent implements OnInit, OnDestroy { height: elemOffset.height }); } else { - if (e.type === 'resize' && this.affixStyle && this.affixStyle.position === 'fixed' && this.placeholderNode.offsetWidth) { + if ( + e.type === 'resize' && + this.affixStyle && + this.affixStyle.position === 'fixed' && + this.placeholderNode.offsetWidth + ) { this.setAffixStyle(e, { ...this.affixStyle, width: this.placeholderNode.offsetWidth }); } else { this.setAffixStyle(e); diff --git a/components/affix/nz-affix.module.ts b/components/affix/nz-affix.module.ts index 0f4b3fc89f9..feeb36d565f 100644 --- a/components/affix/nz-affix.module.ts +++ b/components/affix/nz-affix.module.ts @@ -6,10 +6,9 @@ import { SCROLL_SERVICE_PROVIDER } from '../core/scroll/nz-scroll.service'; import { NzAffixComponent } from './nz-affix.component'; @NgModule({ - declarations: [ NzAffixComponent ], - exports : [ NzAffixComponent ], - imports : [ CommonModule ], - providers : [ SCROLL_SERVICE_PROVIDER ] + declarations: [NzAffixComponent], + exports: [NzAffixComponent], + imports: [CommonModule], + providers: [SCROLL_SERVICE_PROVIDER] }) -export class NzAffixModule { -} +export class NzAffixModule {} diff --git a/components/alert/demo/banner.ts b/components/alert/demo/banner.ts index f7a6d1cf846..9bbac47dd12 100644 --- a/components/alert/demo/banner.ts +++ b/components/alert/demo/banner.ts @@ -4,17 +4,20 @@ import { Component } from '@angular/core'; selector: 'nz-demo-alert-banner', template: ` - + `, - styles : [ - ` + styles: [ + ` nz-alert { margin-bottom: 12px; } ` ] }) -export class NzDemoAlertBannerComponent { -} +export class NzDemoAlertBannerComponent {} diff --git a/components/alert/demo/basic.ts b/components/alert/demo/basic.ts index ad58a939bd8..60b3f5e0bfa 100644 --- a/components/alert/demo/basic.ts +++ b/components/alert/demo/basic.ts @@ -1,10 +1,9 @@ import { Component } from '@angular/core'; @Component({ - selector : 'nz-demo-alert-basic', - template : ` + selector: 'nz-demo-alert-basic', + template: ` ` }) -export class NzDemoAlertBasicComponent { -} +export class NzDemoAlertBasicComponent {} diff --git a/components/alert/demo/closable.ts b/components/alert/demo/closable.ts index 64e1772276f..121c7d84feb 100644 --- a/components/alert/demo/closable.ts +++ b/components/alert/demo/closable.ts @@ -7,18 +7,20 @@ import { Component } from '@angular/core'; nzType="warning" nzCloseable nzMessage="Warning Text Warning Text Warning Text Warning Text Warning Text Warning Text Warning Text" - (nzOnClose)="afterClose()"> + (nzOnClose)="afterClose()" + > + (nzOnClose)="afterClose()" + > `, - styles : [ - ` + styles: [ + ` nz-alert { margin-bottom: 16px; } diff --git a/components/alert/demo/close-text.ts b/components/alert/demo/close-text.ts index 4b0cb15021e..d3054beeb07 100644 --- a/components/alert/demo/close-text.ts +++ b/components/alert/demo/close-text.ts @@ -6,5 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoAlertCloseTextComponent { -} +export class NzDemoAlertCloseTextComponent {} diff --git a/components/alert/demo/description.ts b/components/alert/demo/description.ts index d8f5ec24e2e..acbd0b53db8 100644 --- a/components/alert/demo/description.ts +++ b/components/alert/demo/description.ts @@ -6,25 +6,29 @@ import { Component } from '@angular/core'; + nzDescription="Success Description Success Description Success Description" + > + nzDescription="Info Description Info Description Info Description Info Description" + > + nzDescription="Warning Description Warning Description Warning Description Warning Description" + > + nzDescription="Error Description Error Description Error Description Error Description" + > `, - styles : [ + styles: [ ` nz-alert { margin-bottom: 16px; @@ -32,5 +36,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoAlertDescriptionComponent { -} +export class NzDemoAlertDescriptionComponent {} diff --git a/components/alert/demo/icon.ts b/components/alert/demo/icon.ts index 6f6e2a99950..b7f726f2fda 100644 --- a/components/alert/demo/icon.ts +++ b/components/alert/demo/icon.ts @@ -11,28 +11,27 @@ import { Component } from '@angular/core'; nzType="success" nzMessage="Success Tips" nzDescription="Detailed description and advices about successful copywriting." - nzShowIcon> + nzShowIcon + > + nzShowIcon + > + nzShowIcon + > - + `, - styles : [ + styles: [ ` nz-alert { margin-bottom: 16px; @@ -40,5 +39,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoAlertIconComponent { -} +export class NzDemoAlertIconComponent {} diff --git a/components/alert/demo/style.ts b/components/alert/demo/style.ts index 85abcdd599e..6091d129197 100644 --- a/components/alert/demo/style.ts +++ b/components/alert/demo/style.ts @@ -8,13 +8,12 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` nz-alert { margin-bottom: 16px; } ` ] }) -export class NzDemoAlertStyleComponent { -} +export class NzDemoAlertStyleComponent {} diff --git a/components/alert/nz-alert.component.ts b/components/alert/nz-alert.component.ts index 0a4ecf6f6ad..d1ed33ced67 100644 --- a/components/alert/nz-alert.component.ts +++ b/components/alert/nz-alert.component.ts @@ -14,16 +14,18 @@ import { NgClassType } from '../core/types/ng-class'; import { InputBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-alert', - animations : [ slideAlertMotion ], - templateUrl : './nz-alert.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: 'nz-alert', + animations: [slideAlertMotion], + templateUrl: './nz-alert.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - styles : [ - `nz-alert { - display: block; - }` + styles: [ + ` + nz-alert { + display: block; + } + ` ] }) export class NzAlertComponent implements OnChanges { diff --git a/components/alert/nz-alert.module.ts b/components/alert/nz-alert.module.ts index 02473ff60ae..8643895fdf8 100644 --- a/components/alert/nz-alert.module.ts +++ b/components/alert/nz-alert.module.ts @@ -6,9 +6,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzAlertComponent } from './nz-alert.component'; @NgModule({ - declarations: [ NzAlertComponent ], - exports : [ NzAlertComponent ], - imports : [ CommonModule, NzIconModule, NzAddOnModule ] + declarations: [NzAlertComponent], + exports: [NzAlertComponent], + imports: [CommonModule, NzIconModule, NzAddOnModule] }) -export class NzAlertModule { -} +export class NzAlertModule {} diff --git a/components/alert/nz-alert.spec.ts b/components/alert/nz-alert.spec.ts index 5c2a04cf1be..94c1ea208e6 100644 --- a/components/alert/nz-alert.spec.ts +++ b/components/alert/nz-alert.spec.ts @@ -9,8 +9,8 @@ import { NzAlertModule } from './nz-alert.module'; describe('alert', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzAlertModule, NoopAnimationsModule ], - declarations: [ NzDemoTestBasicComponent, NzDemoTestBannerComponent ] + imports: [NzAlertModule, NoopAnimationsModule], + declarations: [NzDemoTestBasicComponent, NzDemoTestBannerComponent] }); TestBed.compileComponents(); })); @@ -91,7 +91,7 @@ describe('alert', () => { expect(alert.nativeElement.querySelector('.ant-alert-icon').classList).toContain('anticon-lock'); }); it('should type work', () => { - const listOfType = [ 'success', 'info', 'warning', 'error' ]; + const listOfType = ['success', 'info', 'warning', 'error']; listOfType.forEach(type => { testComponent.type = type; fixture.detectChanges(); @@ -130,7 +130,8 @@ describe('alert', () => { [nzShowIcon]="showIcon" [nzIconType]="iconType" [nzType]="type" - (nzOnClose)="onClose($event)"> + (nzOnClose)="onClose($event)" + > ` }) @@ -150,9 +151,7 @@ export class NzDemoTestBasicComponent { @Component({ selector: 'nz-test-alert-banner', template: ` - - + ` }) -export class NzDemoTestBannerComponent { -} +export class NzDemoTestBannerComponent {} diff --git a/components/anchor/anchor.spec.ts b/components/anchor/anchor.spec.ts index 6f435f0ea58..5981a9e00aa 100644 --- a/components/anchor/anchor.spec.ts +++ b/components/anchor/anchor.spec.ts @@ -16,8 +16,8 @@ describe('anchor', () => { let srv: NzScrollService; beforeEach(() => { const i = TestBed.configureTestingModule({ - imports: [ NzAnchorModule ], - declarations: [ TestComponent ] + imports: [NzAnchorModule], + declarations: [TestComponent] }); fixture = TestBed.createComponent(TestComponent); dl = fixture.debugElement; @@ -31,14 +31,13 @@ describe('anchor', () => { describe('[default]', () => { it(`should scolling to target via click a link`, () => { - spyOn(srv, 'scrollTo').and.callFake(( - _containerEl: Element | Window, - _targetTopValue: number = 0, - _easing?: any, - callback?: () => void - ) => { - if (callback) { callback(); } - }); + spyOn(srv, 'scrollTo').and.callFake( + (_containerEl: Element | Window, _targetTopValue: number = 0, _easing?: any, callback?: () => void) => { + if (callback) { + callback(); + } + } + ); expect(context._scroll).not.toHaveBeenCalled(); page.to('#何时使用'); expect(context._scroll).toHaveBeenCalled(); @@ -223,56 +222,58 @@ describe('anchor', () => { return this; } } - }); @Component({ template: ` - - - - - - tpl - - - - - - - tpl-title + + + + + + tpl - - - - - - - -

-
-

-
-

-
-

-
- - - - - - -

parallel1

parallel2

-
-
+ + + + + tpl-title + + + + + + + + + +

+
+

+
+

+
+

+
+ + + + + + +

parallel1

parallel2

+ +
+
` }) export class TestComponent { diff --git a/components/anchor/demo/basic.ts b/components/anchor/demo/basic.ts index 8c9063bc8b8..63ffc9362fa 100755 --- a/components/anchor/demo/basic.ts +++ b/components/anchor/demo/basic.ts @@ -13,4 +13,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoAnchorBasicComponent { } +export class NzDemoAnchorBasicComponent {} diff --git a/components/anchor/demo/static.ts b/components/anchor/demo/static.ts index aaa8bd2d851..40c3734cddf 100644 --- a/components/anchor/demo/static.ts +++ b/components/anchor/demo/static.ts @@ -1,9 +1,9 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-anchor-static', + selector: 'nz-demo-anchor-static', encapsulation: ViewEncapsulation.None, - template : ` + template: ` @@ -14,5 +14,4 @@ import { Component, ViewEncapsulation } from '@angular/core'; ` }) -export class NzDemoAnchorStaticComponent { -} +export class NzDemoAnchorStaticComponent {} diff --git a/components/anchor/nz-anchor-link.component.ts b/components/anchor/nz-anchor-link.component.ts index 1c664cc6f1e..a63581eae74 100644 --- a/components/anchor/nz-anchor-link.component.ts +++ b/components/anchor/nz-anchor-link.component.ts @@ -6,7 +6,8 @@ import { ElementRef, Input, OnDestroy, - OnInit, Renderer2, + OnInit, + Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -14,22 +15,23 @@ import { import { NzAnchorComponent } from './nz-anchor.component'; @Component({ - selector : 'nz-link', + selector: 'nz-link', preserveWhitespaces: false, - templateUrl : './nz-anchor-link.component.html', - host : { + templateUrl: './nz-anchor-link.component.html', + host: { '[class.ant-anchor-link-active]': 'active' }, - styles : [ ` - nz-link { - display: block; - } - ` ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + styles: [ + ` + nz-link { + display: block; + } + ` + ], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzAnchorLinkComponent implements OnInit, OnDestroy { - @Input() nzHref = '#'; titleStr: string | null = ''; @@ -48,7 +50,12 @@ export class NzAnchorLinkComponent implements OnInit, OnDestroy { @ContentChild('nzTemplate') nzTemplate: TemplateRef; - constructor(public elementRef: ElementRef, private anchorComp: NzAnchorComponent, private cdr: ChangeDetectorRef, renderer: Renderer2) { + constructor( + public elementRef: ElementRef, + private anchorComp: NzAnchorComponent, + private cdr: ChangeDetectorRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-anchor-link'); } @@ -69,5 +76,4 @@ export class NzAnchorLinkComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.anchorComp.unregisterLink(this); } - } diff --git a/components/anchor/nz-anchor.component.ts b/components/anchor/nz-anchor.component.ts index 17dd104c183..dc3d6fe32e4 100644 --- a/components/anchor/nz-anchor.component.ts +++ b/components/anchor/nz-anchor.component.ts @@ -29,11 +29,11 @@ interface Section { const sharpMatcherRegx = /#([^#]+)$/; @Component({ - selector : 'nz-anchor', + selector: 'nz-anchor', preserveWhitespaces: false, - templateUrl : './nz-anchor.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + templateUrl: './nz-anchor.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzAnchorComponent implements OnDestroy, AfterViewInit { @ViewChild('ink') private ink: ElementRef; @@ -75,8 +75,7 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { private destroyed = false; /* tslint:disable-next-line:no-any */ - constructor(private scrollSrv: NzScrollService, @Inject(DOCUMENT) private doc: any, private cdr: ChangeDetectorRef) { - } + constructor(private scrollSrv: NzScrollService, @Inject(DOCUMENT) private doc: any, private cdr: ChangeDetectorRef) {} registerLink(link: NzAnchorLinkComponent): void { this.links.push(link); @@ -102,7 +101,10 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { private registerScrollEvent(): void { this.removeListen(); this.scroll$ = fromEvent(this.getTarget(), 'scroll') - .pipe(throttleTime(50), distinctUntilChanged()) + .pipe( + throttleTime(50), + distinctUntilChanged() + ) .subscribe(() => this.handleScroll()); // 浏览器在刷新时保持滚动位置,会倒置在dom未渲染完成时计算不正确,因此延迟重新计算 // 与之相对应可能会引起组件移除后依然触发 `handleScroll` 的 `detectChanges` @@ -138,7 +140,7 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { if (!sharpLinkMatch) { return; } - const target = this.doc.getElementById(sharpLinkMatch[ 1 ]); + const target = this.doc.getElementById(sharpLinkMatch[1]); if (target && this.getOffsetTop(target) < scope) { const top = this.getOffsetTop(target); sections.push({ @@ -153,7 +155,7 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { this.clearActive(); this.cdr.detectChanges(); } else { - const maxSection = sections.reduce((prev, curr) => curr.top > prev.top ? curr : prev); + const maxSection = sections.reduce((prev, curr) => (curr.top > prev.top ? curr : prev)); this.handleActive(maxSection.comp); } } @@ -171,7 +173,9 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { comp.active = true; comp.markForCheck(); - const linkNode = (comp.elementRef.nativeElement as HTMLDivElement).querySelector('.ant-anchor-link-title') as HTMLElement; + const linkNode = (comp.elementRef.nativeElement as HTMLDivElement).querySelector( + '.ant-anchor-link-title' + ) as HTMLElement; this.ink.nativeElement.style.top = `${linkNode.offsetTop + linkNode.clientHeight / 2 - 4.5}px`; this.cdr.detectChanges(); @@ -194,5 +198,4 @@ export class NzAnchorComponent implements OnDestroy, AfterViewInit { }); this.nzClick.emit(linkComp.nzHref); } - } diff --git a/components/anchor/nz-anchor.module.ts b/components/anchor/nz-anchor.module.ts index 9b9766c44bf..8fdc029047e 100644 --- a/components/anchor/nz-anchor.module.ts +++ b/components/anchor/nz-anchor.module.ts @@ -8,10 +8,9 @@ import { NzAnchorLinkComponent } from './nz-anchor-link.component'; import { NzAnchorComponent } from './nz-anchor.component'; @NgModule({ - declarations: [ NzAnchorComponent, NzAnchorLinkComponent ], - exports : [ NzAnchorComponent, NzAnchorLinkComponent ], - imports : [ CommonModule, NzAffixModule ], - providers : [ SCROLL_SERVICE_PROVIDER ] + declarations: [NzAnchorComponent, NzAnchorLinkComponent], + exports: [NzAnchorComponent, NzAnchorLinkComponent], + imports: [CommonModule, NzAffixModule], + providers: [SCROLL_SERVICE_PROVIDER] }) -export class NzAnchorModule { -} +export class NzAnchorModule {} diff --git a/components/auto-complete/demo/basic.ts b/components/auto-complete/demo/basic.ts index f56e32049ee..6c23e879be5 100644 --- a/components/auto-complete/demo/basic.ts +++ b/components/auto-complete/demo/basic.ts @@ -1,28 +1,30 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-basic', + selector: 'nz-demo-auto-complete-basic', encapsulation: ViewEncapsulation.None, - template : ` + template: `
- + - - {{option}} - + + {{ option }} +
-` + ` }) export class NzDemoAutoCompleteBasicComponent { inputValue: string; options: string[] = []; onInput(value: string): void { - this.options = value ? [ - value, - value + value, - value + value + value - ] : []; + this.options = value ? [value, value + value, value + value + value] : []; } } diff --git a/components/auto-complete/demo/certain-category.ts b/components/auto-complete/demo/certain-category.ts index a828ee1434a..91bec05f448 100644 --- a/components/auto-complete/demo/certain-category.ts +++ b/components/auto-complete/demo/certain-category.ts @@ -1,13 +1,19 @@ import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-certain-category', + selector: 'nz-demo-auto-complete-certain-category', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - template : ` + template: `
- + @@ -15,29 +21,32 @@ import { ChangeDetectionStrategy, Component, OnInit, ViewEncapsulation } from '@ - {{group.title}} + {{ group.title }} 更多 - {{option.title}} - {{option.count}} 人 关注 + {{ option.title }} + {{ option.count }} 人 关注
-`, - styles: [` - .certain-search-item-count { - position: absolute; - color: #999; - right: 16px; - } + `, + styles: [ + ` + .certain-search-item-count { + position: absolute; + color: #999; + right: 16px; + } - .more-link { - float: right; - } - `] + .more-link { + float: right; + } + ` + ] }) export class NzDemoAutoCompleteCertainCategoryComponent implements OnInit { inputValue: string; @@ -49,32 +58,43 @@ export class NzDemoAutoCompleteCertainCategoryComponent implements OnInit { ngOnInit(): void { setTimeout(() => { - this.optionGroups = [{ - title: '话题', - children: [{ - title: 'AntDesign', - count: 10000 - }, { - title: 'AntDesign UI', - count: 10600 - }] - }, { - title: '问题', - children: [{ - title: 'AntDesign UI 有多好', - count: 60100 - }, { - title: 'AntDesign 是啥', - count: 30010 - }] - }, { - title: '文章', - children: [{ - title: 'AntDesign 是一个设计语言', - count: 100000 - }] - }]; + this.optionGroups = [ + { + title: '话题', + children: [ + { + title: 'AntDesign', + count: 10000 + }, + { + title: 'AntDesign UI', + count: 10600 + } + ] + }, + { + title: '问题', + children: [ + { + title: 'AntDesign UI 有多好', + count: 60100 + }, + { + title: 'AntDesign 是啥', + count: 30010 + } + ] + }, + { + title: '文章', + children: [ + { + title: 'AntDesign 是一个设计语言', + count: 100000 + } + ] + } + ]; }, 1000); } - } diff --git a/components/auto-complete/demo/custom.ts b/components/auto-complete/demo/custom.ts index 0be5394e1fb..d322052429d 100644 --- a/components/auto-complete/demo/custom.ts +++ b/components/auto-complete/demo/custom.ts @@ -1,26 +1,29 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-custom', + selector: 'nz-demo-auto-complete-custom', encapsulation: ViewEncapsulation.None, - template : ` + template: `
- + - {{option}} + {{ option }}
-` + ` }) export class NzDemoAutoCompleteCustomComponent { inputValue: string; options: string[] = []; onInput(value: string): void { - this.options = value ? [ - value, - value + value, - value + value + value - ] : []; + this.options = value ? [value, value + value, value + value + value] : []; } } diff --git a/components/auto-complete/demo/non-case-sensitive.ts b/components/auto-complete/demo/non-case-sensitive.ts index 8429d910c0f..5297692399c 100644 --- a/components/auto-complete/demo/non-case-sensitive.ts +++ b/components/auto-complete/demo/non-case-sensitive.ts @@ -1,15 +1,20 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-non-case-sensitive', + selector: 'nz-demo-auto-complete-non-case-sensitive', encapsulation: ViewEncapsulation.None, - template : ` + template: `
- - - + +
-` + ` }) export class NzDemoAutoCompleteNonCaseSensitiveComponent { inputValue: string; @@ -21,7 +26,6 @@ export class NzDemoAutoCompleteNonCaseSensitiveComponent { } onInput(value: string): void { - this.filteredOptions = this.options - .filter(option => option.toLowerCase().indexOf(value.toLowerCase()) === 0); + this.filteredOptions = this.options.filter(option => option.toLowerCase().indexOf(value.toLowerCase()) === 0); } } diff --git a/components/auto-complete/demo/options.ts b/components/auto-complete/demo/options.ts index d9721441380..f2e29ddfaa7 100644 --- a/components/auto-complete/demo/options.ts +++ b/components/auto-complete/demo/options.ts @@ -1,16 +1,22 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-options', + selector: 'nz-demo-auto-complete-options', encapsulation: ViewEncapsulation.None, - template : ` + template: `
- + - {{option}} + {{ option }}
-` + ` }) export class NzDemoAutoCompleteOptionsComponent { inputValue: string; diff --git a/components/auto-complete/demo/uncertain-category.ts b/components/auto-complete/demo/uncertain-category.ts index c298d8f82f0..18a00f476f9 100644 --- a/components/auto-complete/demo/uncertain-category.ts +++ b/components/auto-complete/demo/uncertain-category.ts @@ -1,48 +1,58 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-auto-complete-uncertain-category', + selector: 'nz-demo-auto-complete-uncertain-category', encapsulation: ViewEncapsulation.None, - template : ` + template: `
- + - + - {{option.value}} 在 - - {{option.category}} + {{ option.value }} 在 + + {{ option.category }} 区块中 - 约 {{option.count}} 个结果 + 约 {{ option.count }} 个结果
-`, - styles: [` - .global-search-item-count { - position: absolute; - right: 16px; - } - `] + `, + styles: [ + ` + .global-search-item-count { + position: absolute; + right: 16px; + } + ` + ] }) export class NzDemoAutoCompleteUncertainCategoryComponent { inputValue: string; - options: Array<{ value: string; category: string; count: number; }> = []; + options: Array<{ value: string; category: string; count: number }> = []; onChange(value: string): void { - this.options = new Array(this.getRandomInt(15, 5)).join('.').split('.') - .map((_item, idx) => ({ - value, - category: `${value}${idx}`, - count: this.getRandomInt(200, 100) - })); + this.options = new Array(this.getRandomInt(15, 5)) + .join('.') + .split('.') + .map((_item, idx) => ({ + value, + category: `${value}${idx}`, + count: this.getRandomInt(200, 100) + })); } private getRandomInt(max: number, min: number = 0): number { diff --git a/components/auto-complete/nz-autocomplete-optgroup.component.ts b/components/auto-complete/nz-autocomplete-optgroup.component.ts index 57634ab7a85..46ce7058c69 100644 --- a/components/auto-complete/nz-autocomplete-optgroup.component.ts +++ b/components/auto-complete/nz-autocomplete-optgroup.component.ts @@ -1,21 +1,18 @@ import { ChangeDetectionStrategy, Component, Input, TemplateRef, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-auto-optgroup', + selector: 'nz-auto-optgroup', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-autocomplete-optgroup.component.html', - host : { - 'role' : 'group', - 'class': 'ant-select-dropdown-menu-item-group' + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-autocomplete-optgroup.component.html', + host: { + role: 'group', + class: 'ant-select-dropdown-menu-item-group' } }) export class NzAutocompleteOptgroupComponent { - @Input() nzLabel: string | TemplateRef; - constructor() { - } - + constructor() {} } diff --git a/components/auto-complete/nz-autocomplete-option.component.ts b/components/auto-complete/nz-autocomplete-option.component.ts index a35b8224213..1ae8f5d45f0 100644 --- a/components/auto-complete/nz-autocomplete-option.component.ts +++ b/components/auto-complete/nz-autocomplete-option.component.ts @@ -13,33 +13,28 @@ import { InputBoolean } from '../core/util/convert'; import { scrollIntoView } from '../core/util/scroll-into-view-if-needed'; export class NzOptionSelectionChange { - constructor( - public source: NzAutocompleteOptionComponent, - public isUserInput: boolean = false - ) { - } + constructor(public source: NzAutocompleteOptionComponent, public isUserInput: boolean = false) {} } @Component({ - selector : 'nz-auto-option', + selector: 'nz-auto-option', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-autocomplete-option.component.html', - host : { - 'role' : 'menuitem', - 'class' : 'ant-select-dropdown-menu-item', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-autocomplete-option.component.html', + host: { + role: 'menuitem', + class: 'ant-select-dropdown-menu-item', '[class.ant-select-dropdown-menu-item-selected]': 'selected', - '[class.ant-select-dropdown-menu-item-active]' : 'active', + '[class.ant-select-dropdown-menu-item-active]': 'active', '[class.ant-select-dropdown-menu-item-disabled]': 'nzDisabled', - '[attr.aria-selected]' : 'selected.toString()', - '[attr.aria-disabled]' : 'nzDisabled.toString()', - '(click)' : 'selectViaInteraction()', - '(mousedown)' : '$event.preventDefault()' + '[attr.aria-selected]': 'selected.toString()', + '[attr.aria-disabled]': 'nzDisabled.toString()', + '(click)': 'selectViaInteraction()', + '(mousedown)': '$event.preventDefault()' } }) export class NzAutocompleteOptionComponent { - /* tslint:disable-next-line:no-any */ @Input() nzValue: any; @Input() nzLabel: string; @@ -49,8 +44,7 @@ export class NzAutocompleteOptionComponent { active = false; selected = false; - constructor(private changeDetectorRef: ChangeDetectorRef, private element: ElementRef) { - } + constructor(private changeDetectorRef: ChangeDetectorRef, private element: ElementRef) {} select(): void { this.selected = true; @@ -105,5 +99,4 @@ export class NzAutocompleteOptionComponent { private emitSelectionChangeEvent(isUserInput: boolean = false): void { this.selectionChange.emit(new NzOptionSelectionChange(this, isUserInput)); } - } diff --git a/components/auto-complete/nz-autocomplete-trigger.directive.ts b/components/auto-complete/nz-autocomplete-trigger.directive.ts index 9d160be0319..bc6e68191d2 100644 --- a/components/auto-complete/nz-autocomplete-trigger.directive.ts +++ b/components/auto-complete/nz-autocomplete-trigger.directive.ts @@ -31,31 +31,32 @@ import { NzAutocompleteOptionComponent } from './nz-autocomplete-option.componen import { NzAutocompleteComponent } from './nz-autocomplete.component'; export const NZ_AUTOCOMPLETE_VALUE_ACCESSOR: ExistingProvider = { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzAutocompleteTriggerDirective), - multi : true + multi: true }; export function getNzAutocompleteMissingPanelError(): Error { - return Error('Attempting to open an undefined instance of `nz-autocomplete`. ' + - 'Make sure that the id passed to the `nzAutocomplete` is correct and that ' + - 'you\'re attempting to open it after the ngAfterContentInit hook.'); + return Error( + 'Attempting to open an undefined instance of `nz-autocomplete`. ' + + 'Make sure that the id passed to the `nzAutocomplete` is correct and that ' + + "you're attempting to open it after the ngAfterContentInit hook." + ); } @Directive({ - selector : `input[nzAutocomplete], textarea[nzAutocomplete]`, - providers: [ NZ_AUTOCOMPLETE_VALUE_ACCESSOR ], - host : { - 'autocomplete' : 'off', + selector: `input[nzAutocomplete], textarea[nzAutocomplete]`, + providers: [NZ_AUTOCOMPLETE_VALUE_ACCESSOR], + host: { + autocomplete: 'off', 'aria-autocomplete': 'list', - '(focusin)' : 'handleFocus()', - '(blur)' : 'handleBlur()', - '(input)' : 'handleInput($event)', - '(keydown)' : 'handleKeydown($event)' + '(focusin)': 'handleFocus()', + '(blur)': 'handleBlur()', + '(input)': 'handleInput($event)', + '(keydown)': 'handleKeydown($event)' } }) export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnDestroy { - /** Bind nzAutocomplete component */ @Input() nzAutocomplete: NzAutocompleteComponent; @@ -85,8 +86,8 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD private _overlay: Overlay, private viewContainerRef: ViewContainerRef, // tslint:disable-next-line:no-any - @Optional() @Inject(DOCUMENT) private document: any) { - } + @Optional() @Inject(DOCUMENT) private document: any + ) {} ngOnDestroy(): void { this.destroyPanel(); @@ -170,8 +171,7 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD if (target.type === 'number') { value = value === '' ? null : parseFloat(value); } - if (this.canOpen() && document.activeElement === event.target && - this.previousValue !== value) { + if (this.canOpen() && document.activeElement === event.target && this.previousValue !== value) { this.previousValue = value; this._onChange(value); this.openPanel(); @@ -194,9 +194,7 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD * Subscription data source changes event */ private subscribeOptionsChange(): Subscription { - return this.nzAutocomplete.options.changes.pipe( - delay(0) - ).subscribe(() => { + return this.nzAutocomplete.options.changes.pipe(delay(0)).subscribe(() => { this.resetActiveItem(); }); } @@ -205,10 +203,9 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD * Subscription option changes event and set the value */ private subscribeSelectionChange(): Subscription { - return this.nzAutocomplete.selectionChange - .subscribe((option: NzAutocompleteOptionComponent) => { - this.setValueAndClose(option); - }); + return this.nzAutocomplete.selectionChange.subscribe((option: NzAutocompleteOptionComponent) => { + this.setValueAndClose(option); + }); } /** @@ -218,15 +215,18 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD return merge( fromEvent(this.document, 'click'), fromEvent(this.document, 'touchend') - ) - .subscribe((event: MouseEvent | TouchEvent) => { - const clickTarget = event.target as HTMLElement; - - // Make sure is not self - if (clickTarget !== this.elementRef.nativeElement && !this.overlayRef!.overlayElement.contains(clickTarget) && this.panelOpen) { - this.closePanel(); - } - }); + ).subscribe((event: MouseEvent | TouchEvent) => { + const clickTarget = event.target as HTMLElement; + + // Make sure is not self + if ( + clickTarget !== this.elementRef.nativeElement && + !this.overlayRef!.overlayElement.contains(clickTarget) && + this.panelOpen + ) { + this.closePanel(); + } + }); } /** @@ -287,9 +287,9 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD private getOverlayConfig(): OverlayConfig { return new OverlayConfig({ positionStrategy: this.getOverlayPosition(), - scrollStrategy : this._overlay.scrollStrategies.reposition(), + scrollStrategy: this._overlay.scrollStrategies.reposition(), // default host element width - width : this.nzAutocomplete.nzWidth || this.getHostWidth() + width: this.nzAutocomplete.nzWidth || this.getHostWidth() }); } @@ -306,7 +306,8 @@ export class NzAutocompleteTriggerDirective implements ControlValueAccessor, OnD new ConnectionPositionPair({ originX: 'start', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' }), new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'bottom' }) ]; - this.positionStrategy = this._overlay.position() + this.positionStrategy = this._overlay + .position() .flexibleConnectedTo(this.getConnectedElement()) .withPositions(positions) .withFlexibleDimensions(false) diff --git a/components/auto-complete/nz-autocomplete.component.ts b/components/auto-complete/nz-autocomplete.component.ts index b2a9617a170..ef5ce12c066 100644 --- a/components/auto-complete/nz-autocomplete.component.ts +++ b/components/auto-complete/nz-autocomplete.component.ts @@ -35,15 +35,13 @@ export interface AutocompleteDataSourceItem { export type AutocompleteDataSource = AutocompleteDataSourceItem[] | string[] | number[]; @Component({ - selector : 'nz-autocomplete', + selector: 'nz-autocomplete', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-autocomplete.component.html', - animations : [ - slideMotion - ], - styles : [ + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-autocomplete.component.html', + animations: [slideMotion], + styles: [ ` .ant-select-dropdown { top: 100%; @@ -57,14 +55,15 @@ export type AutocompleteDataSource = AutocompleteDataSourceItem[] | string[] | n ] }) export class NzAutocompleteComponent implements AfterViewInit, OnDestroy { - @Input() nzWidth: number; @Input() nzOverlayClassName = ''; - @Input() nzOverlayStyle: { [ key: string ]: string } = {}; + @Input() nzOverlayStyle: { [key: string]: string } = {}; @Input() @InputBoolean() nzDefaultActiveFirstOption = true; @Input() @InputBoolean() nzBackfill = false; @Input() nzDataSource: AutocompleteDataSource; - @Output() readonly selectionChange: EventEmitter = new EventEmitter(); + @Output() readonly selectionChange: EventEmitter = new EventEmitter< + NzAutocompleteOptionComponent + >(); showPanel: boolean = false; isOpen: boolean = false; @@ -84,7 +83,9 @@ export class NzAutocompleteComponent implements AfterViewInit, OnDestroy { } /** Provided by content */ - @ContentChildren(NzAutocompleteOptionComponent, { descendants: true }) fromContentOptions: QueryList; + @ContentChildren(NzAutocompleteOptionComponent, { descendants: true }) fromContentOptions: QueryList< + NzAutocompleteOptionComponent + >; /** Provided by dataSource */ @ViewChildren(NzAutocompleteOptionComponent) fromDataSourceOptions: QueryList; @@ -101,14 +102,17 @@ export class NzAutocompleteComponent implements AfterViewInit, OnDestroy { if (this.options) { return merge(...this.options.map(option => option.selectionChange)); } - return this.ngZone.onStable - .asObservable() - .pipe(take(1), switchMap(() => this.optionSelectionChanges)); + return this.ngZone.onStable.asObservable().pipe( + take(1), + switchMap(() => this.optionSelectionChanges) + ); }); - constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + constructor( + private changeDetectorRef: ChangeDetectorRef, + private ngZone: NgZone, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngAfterViewInit(): void { this.optionsInit(); @@ -125,7 +129,7 @@ export class NzAutocompleteComponent implements AfterViewInit, OnDestroy { } setActiveItem(index: number): void { - const activeItem = this.options.toArray()[ index ]; + const activeItem = this.options.toArray()[index]; if (activeItem && !activeItem.active) { this.activeItem = activeItem; this.activeItemIndex = index; @@ -182,14 +186,14 @@ export class NzAutocompleteComponent implements AfterViewInit, OnDestroy { private subscribeOptionChanges(): void { this.selectionChangeSubscription.unsubscribe(); this.selectionChangeSubscription = this.optionSelectionChanges - .pipe(filter((event: NzOptionSelectionChange) => event.isUserInput)) - .subscribe((event: NzOptionSelectionChange) => { - event.source.select(); - event.source.setActiveStyles(); - this.activeItem = event.source; - this.activeItemIndex = this.getOptionIndex(this.activeItem); - this.clearSelectedOptions(event.source, true); - this.selectionChange.emit(event.source); - }); + .pipe(filter((event: NzOptionSelectionChange) => event.isUserInput)) + .subscribe((event: NzOptionSelectionChange) => { + event.source.select(); + event.source.setActiveStyles(); + this.activeItem = event.source; + this.activeItemIndex = this.getOptionIndex(this.activeItem); + this.clearSelectedOptions(event.source, true); + this.selectionChange.emit(event.source); + }); } } diff --git a/components/auto-complete/nz-autocomplete.module.ts b/components/auto-complete/nz-autocomplete.module.ts index a02ef654794..4657c7105c1 100644 --- a/components/auto-complete/nz-autocomplete.module.ts +++ b/components/auto-complete/nz-autocomplete.module.ts @@ -12,9 +12,18 @@ import { NzAutocompleteTriggerDirective } from './nz-autocomplete-trigger.direct import { NzAutocompleteComponent } from './nz-autocomplete.component'; @NgModule({ - declarations: [NzAutocompleteComponent, NzAutocompleteOptionComponent, NzAutocompleteTriggerDirective, NzAutocompleteOptgroupComponent], - exports: [NzAutocompleteComponent, NzAutocompleteOptionComponent, NzAutocompleteTriggerDirective, NzAutocompleteOptgroupComponent], + declarations: [ + NzAutocompleteComponent, + NzAutocompleteOptionComponent, + NzAutocompleteTriggerDirective, + NzAutocompleteOptgroupComponent + ], + exports: [ + NzAutocompleteComponent, + NzAutocompleteOptionComponent, + NzAutocompleteTriggerDirective, + NzAutocompleteOptgroupComponent + ], imports: [CommonModule, OverlayModule, FormsModule, NzAddOnModule, NzNoAnimationModule] }) -export class NzAutocompleteModule { -} +export class NzAutocompleteModule {} diff --git a/components/auto-complete/nz-autocomplete.spec.ts b/components/auto-complete/nz-autocomplete.spec.ts index cd2ce6d357b..181b1148584 100644 --- a/components/auto-complete/nz-autocomplete.spec.ts +++ b/components/auto-complete/nz-autocomplete.spec.ts @@ -2,15 +2,7 @@ import { Directionality } from '@angular/cdk/bidi'; import { DOWN_ARROW, ENTER, ESCAPE, TAB, UP_ARROW } from '@angular/cdk/keycodes'; import { OverlayContainer } from '@angular/cdk/overlay'; import { ScrollDispatcher } from '@angular/cdk/scrolling'; -import { - ChangeDetectionStrategy, - Component, - NgZone, - OnInit, - QueryList, - ViewChild, - ViewChildren -} from '@angular/core'; +import { ChangeDetectionStrategy, Component, NgZone, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { async, fakeAsync, flush, inject, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, FormBuilder, FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; @@ -42,7 +34,7 @@ describe('auto-complete', () => { beforeEach(async(() => { const dir = 'ltr'; TestBed.configureTestingModule({ - imports : [ NzAutocompleteModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule ], + imports: [NzAutocompleteModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule], declarations: [ NzTestSimpleAutocompleteComponent, NzTestAutocompletePropertyComponent, @@ -51,24 +43,27 @@ describe('auto-complete', () => { NzTestAutocompleteWithOnPushDelayComponent, NzTestAutocompleteWithFormComponent ], - providers : [ + providers: [ { provide: Directionality, useFactory: () => ({ value: dir }) }, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject }) }, - {provide: NgZone, useFactory: () => { + { + provide: NgZone, + useFactory: () => { zone = new MockNgZone(); return zone; - }} + } + } ] }); TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -84,16 +79,13 @@ describe('auto-complete', () => { }); it('should open the panel when the input is focused', () => { - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); - expect(overlayContainerElement.textContent) - .toContain('Burns Bay Road'); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); + expect(overlayContainerElement.textContent).toContain('Burns Bay Road'); }); it('should not open the panel on focus if the input is readonly', fakeAsync(() => { @@ -123,16 +115,13 @@ describe('auto-complete', () => { })); it('should open the panel programmatically', () => { - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); - expect(overlayContainerElement.textContent) - .toContain('Burns Bay Road'); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); + expect(overlayContainerElement.textContent).toContain('Burns Bay Road'); }); it('should close the panel programmatically', fakeAsync(() => { @@ -143,10 +132,8 @@ describe('auto-complete', () => { fixture.detectChanges(); tick(500); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); - expect(overlayContainerElement.textContent) - .toEqual(''); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); + expect(overlayContainerElement.textContent).toEqual(''); })); it('should close the panel when the user clicks away', fakeAsync(() => { @@ -154,13 +141,11 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); dispatchFakeEvent(document, 'click'); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); })); it('should close the panel when the trigger blur', fakeAsync(() => { @@ -168,13 +153,11 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); dispatchFakeEvent(input, 'blur'); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); })); it('should not close the panel when the user clicks this input', fakeAsync(() => { @@ -182,13 +165,11 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); dispatchFakeEvent(input, 'click'); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); })); it('should not throw when attempting to close the panel of a destroyed autocomplete', () => { @@ -208,8 +189,7 @@ describe('auto-complete', () => { flush(); dispatchFakeEvent(document, 'touchend'); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); })); it('should close the panel when an option is clicked', fakeAsync(() => { @@ -222,10 +202,8 @@ describe('auto-complete', () => { fixture.detectChanges(); tick(500); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); - expect(overlayContainerElement.textContent) - .toEqual(''); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); + expect(overlayContainerElement.textContent).toEqual(''); })); it('should close the panel when an option is tap', fakeAsync(() => { @@ -239,10 +217,8 @@ describe('auto-complete', () => { fixture.detectChanges(); tick(500); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); - expect(overlayContainerElement.textContent) - .toEqual(''); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); + expect(overlayContainerElement.textContent).toEqual(''); })); it('should hide the panel when the options list is empty', fakeAsync(() => { @@ -256,19 +232,15 @@ describe('auto-complete', () => { tick(150); fixture.detectChanges(); - expect(panel.classList) - .not - .toContain('ant-select-dropdown-hidden'); + expect(panel.classList).not.toContain('ant-select-dropdown-hidden'); typeInElement('x', input); fixture.detectChanges(); tick(150); fixture.detectChanges(); - expect(panel.classList) - .toContain('ant-select-dropdown-hidden'); + expect(panel.classList).toContain('ant-select-dropdown-hidden'); })); - }); describe('property', () => { @@ -285,20 +257,16 @@ describe('auto-complete', () => { DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); ENTER_EVENT = createKeyboardEvent('keydown', ENTER); TAB_EVENT = createKeyboardEvent('keydown', TAB); - }); it('should open the panel when the input is focused', () => { - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(false); + expect(fixture.componentInstance.trigger.panelOpen).toBe(false); dispatchFakeEvent(input, 'focusin'); fixture.detectChanges(); - expect(fixture.componentInstance.trigger.panelOpen) - .toBe(true); - expect(overlayContainerElement.textContent) - .toContain('Burns Bay Road'); + expect(fixture.componentInstance.trigger.panelOpen).toBe(true); + expect(overlayContainerElement.textContent).toContain('Burns Bay Road'); }); it('should have correct width when setting', () => { @@ -319,16 +287,13 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); flush(); - expect(input.value) - .toBe('Burns Bay Road'); - + expect(input.value).toBe('Burns Bay Road'); })); it('should reset the backfilled value display when pressing tabbing', fakeAsync(() => { @@ -337,20 +302,17 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); - expect(input.value) - .toBe('Burns Bay Road'); + expect(input.value).toBe('Burns Bay Road'); componentInstance.trigger.handleKeydown(TAB_EVENT); fixture.detectChanges(); - expect(input.value) - .not.toBe('Burns Bay Road'); + expect(input.value).not.toBe('Burns Bay Road'); componentInstance.trigger.openPanel(); fixture.detectChanges(); @@ -361,8 +323,7 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(input.value) - .toBe('Downing Street'); + expect(input.value).toBe('Downing Street'); componentInstance.trigger.openPanel(); fixture.detectChanges(); @@ -374,9 +335,7 @@ describe('auto-complete', () => { tick(500); flush(); fixture.detectChanges(); - expect(input.value) - .toBe('Downing Street'); - + expect(input.value).toBe('Downing Street'); })); it('should overlayClassName & overlayStyle work', () => { @@ -391,7 +350,6 @@ describe('auto-complete', () => { expect(dropdown.classList.contains(`testClass`)).toBe(true); expect(dropdown.style.color).toBe(`rgb(1, 2, 3)`); }); - }); describe('value', () => { @@ -410,14 +368,12 @@ describe('auto-complete', () => { flush(); fixture.detectChanges(); - const options = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const options = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; options[1].click(); flush(); fixture.detectChanges(); - expect(fixture.componentInstance.inputControl.value) - .toEqual('Downing Street'); + expect(fixture.componentInstance.inputControl.value).toEqual('Downing Street'); })); it('should update number-input value when option is selected with option value', fakeAsync(() => { @@ -429,14 +385,12 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - const options = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const options = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; options[1].click(); fixture.detectChanges(); flush(); - expect(input.value) - .toBe('200'); + expect(input.value).toBe('200'); })); it('should handle autocomplete being attached to number inputs', fakeAsync(() => { @@ -454,15 +408,12 @@ describe('auto-complete', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); - expect(fixture.componentInstance.inputControl.touched) - .toBe(false); + expect(fixture.componentInstance.inputControl.touched).toBe(false); dispatchFakeEvent(input, 'blur'); fixture.detectChanges(); flush(); - expect(fixture.componentInstance.inputControl.touched) - .toBe(true); + expect(fixture.componentInstance.inputControl.touched).toBe(true); })); - }); describe('form', () => { @@ -478,10 +429,8 @@ describe('auto-complete', () => { it('should set the value with form', () => { const componentInstance = fixture.componentInstance; fixture.detectChanges(); - expect(componentInstance.form.get('formControl')!.value) - .toContain('Burns'); - expect(input.value) - .toContain('Burns'); + expect(componentInstance.form.get('formControl')!.value).toContain('Burns'); + expect(input.value).toContain('Burns'); }); it('should set disabled work', () => { @@ -495,7 +444,6 @@ describe('auto-complete', () => { fixture.detectChanges(); expect(input.disabled).toBe(true); - }); it('should close the panel when the input is disabled', () => { @@ -513,7 +461,6 @@ describe('auto-complete', () => { expect(input.disabled).toBe(true); expect(componentInstance.trigger.panelOpen).toBe(false); - }); }); @@ -540,8 +487,7 @@ describe('auto-complete', () => { it('should fill the text field when an option is selected with ENTER', fakeAsync(() => { const componentInstance = fixture.componentInstance; - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); [1, 2, 3].forEach(() => { componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT); @@ -551,52 +497,43 @@ describe('auto-complete', () => { componentInstance.trigger.handleKeydown(ENTER_EVENT); fixture.detectChanges(); flush(); - expect(componentInstance.inputValue) - .toContain('AntDesign four'); - - expect(input.value) - .toContain('AntDesign four'); + expect(componentInstance.inputValue).toContain('AntDesign four'); + expect(input.value).toContain('AntDesign four'); })); - }); describe('Option selection', () => { let fixture: ComponentFixture; - beforeEach((() => { + beforeEach(() => { fixture = TestBed.createComponent(NzTestSimpleAutocompleteComponent); fixture.detectChanges(); - })); + }); it('should deselect any other selected option', fakeAsync(() => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); - let options = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + let options = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; options[0].click(); fixture.detectChanges(); zone.simulateZoneExit(); fixture.detectChanges(); const componentOptions = fixture.componentInstance.optionComponents.toArray(); - expect(componentOptions[0].selected) - .toBe(true); + expect(componentOptions[0].selected).toBe(true); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); - options = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + options = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; options[1].click(); fixture.detectChanges(); flush(); - expect(componentOptions[0].selected) - .toBe(false); - expect(componentOptions[1].selected) - .toBe(true); + expect(componentOptions[0].selected).toBe(false); + expect(componentOptions[1].selected).toBe(true); })); it('should not deselect when repeat selected option', fakeAsync(() => { @@ -610,21 +547,17 @@ describe('auto-complete', () => { fixture.detectChanges(); const componentOptions = fixture.componentInstance.optionComponents.toArray(); - expect(componentOptions[0].selected) - .toBe(true); + expect(componentOptions[0].selected).toBe(true); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); - options = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + options = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; options[0].click(); fixture.detectChanges(); flush(); - expect(componentOptions[0].selected) - .toBe(true); + expect(componentOptions[0].selected).toBe(true); })); - }); describe('keyboard events', () => { @@ -646,48 +579,39 @@ describe('auto-complete', () => { fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); flush(); - })); it('should set the active item to the second option when DOWN key is pressed', () => { const componentInstance = fixture.componentInstance; - const optionEls = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); expect(optionEls[0].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[1].classList).toContain('ant-select-dropdown-menu-item-active'); - }); it('should set the active item to the first option when DOWN key is pressed in last item', () => { const componentInstance = fixture.componentInstance; - const optionEls = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); [1, 2, 3].forEach(() => componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT)); fixture.detectChanges(); expect(optionEls[1].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[0].classList).toContain('ant-select-dropdown-menu-item-active'); - }); it('should set the active item to the last option when UP key is pressed', () => { const componentInstance = fixture.componentInstance; - const optionEls = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); componentInstance.trigger.handleKeydown(UP_ARROW_EVENT); fixture.detectChanges(); @@ -695,16 +619,13 @@ describe('auto-complete', () => { expect(optionEls[0].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[1].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[2].classList).toContain('ant-select-dropdown-menu-item-active'); - }); it('should set the active item to the previous option when UP key is pressed', () => { const componentInstance = fixture.componentInstance; - const optionEls = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; - expect(componentInstance.trigger.panelOpen) - .toBe(true); + expect(componentInstance.trigger.panelOpen).toBe(true); [1, 2].forEach(() => componentInstance.trigger.handleKeydown(UP_ARROW_EVENT)); fixture.detectChanges(); @@ -712,7 +633,6 @@ describe('auto-complete', () => { expect(optionEls[0].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[1].classList).toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[2].classList).not.toContain('ant-select-dropdown-menu-item-active'); - }); it('should set the active item properly after filtering', () => { @@ -724,36 +644,33 @@ describe('auto-complete', () => { componentInstance.trigger.handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); - const optionEls = - overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('nz-auto-option') as NodeListOf; expect(optionEls[0].classList).not.toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[1].classList).toContain('ant-select-dropdown-menu-item-active'); expect(optionEls[1].innerText).toEqual('Wall Street'); - }); - it('should not open the panel if the `input` event was dispatched with changing the value', - fakeAsync(() => { - const trigger = fixture.componentInstance.trigger; + it('should not open the panel if the `input` event was dispatched with changing the value', fakeAsync(() => { + const trigger = fixture.componentInstance.trigger; - dispatchFakeEvent(input, 'focusin'); - typeInElement('A', input); - fixture.detectChanges(); + dispatchFakeEvent(input, 'focusin'); + typeInElement('A', input); + fixture.detectChanges(); - expect(trigger.panelOpen).toBe(true); + expect(trigger.panelOpen).toBe(true); - trigger.closePanel(); - fixture.detectChanges(); + trigger.closePanel(); + fixture.detectChanges(); - expect(trigger.panelOpen).toBe(false); + expect(trigger.panelOpen).toBe(false); - dispatchFakeEvent(input, 'input'); - fixture.detectChanges(); - flush(); + dispatchFakeEvent(input, 'input'); + fixture.detectChanges(); + flush(); - expect(trigger.panelOpen).toBe(false); - })); + expect(trigger.panelOpen).toBe(false); + })); it('should fill the text field when an option is selected with ENTER', fakeAsync(() => { const componentInstance = fixture.componentInstance; @@ -765,12 +682,9 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(componentInstance.inputControl.value) - .toContain('Downing Street'); - - expect(input.value) - .toContain('Downing Street'); + expect(componentInstance.inputControl.value).toContain('Downing Street'); + expect(input.value).toContain('Downing Street'); })); it('should prevent the default enter key action', fakeAsync(() => { @@ -781,8 +695,7 @@ describe('auto-complete', () => { fixture.detectChanges(); flush(); - expect(ENTER_EVENT.defaultPrevented) - .toBe(true); + expect(ENTER_EVENT.defaultPrevented).toBe(true); })); it('should not prevent the default enter action for a closed panel after a user action', () => { @@ -801,15 +714,13 @@ describe('auto-complete', () => { input.focus(); flush(); - expect(overlayContainerElement.querySelector('.ant-select-dropdown')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-select-dropdown')).toBeTruthy(); dispatchKeyboardEvent(input, 'keydown', TAB); fixture.detectChanges(); tick(500); - expect(overlayContainerElement.querySelector('.ant-select-dropdown')) - .toBeFalsy(); + expect(overlayContainerElement.querySelector('.ant-select-dropdown')).toBeFalsy(); })); it('should close the panel when pressing escape', fakeAsync(() => { @@ -817,17 +728,14 @@ describe('auto-complete', () => { input.focus(); flush(); - expect(overlayContainerElement.querySelector('.ant-select-dropdown')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-select-dropdown')).toBeTruthy(); dispatchKeyboardEvent(input, 'keydown', ESCAPE); fixture.detectChanges(); tick(500); - expect(overlayContainerElement.querySelector('.ant-select-dropdown')) - .toBeFalsy(); + expect(overlayContainerElement.querySelector('.ant-select-dropdown')).toBeFalsy(); })); - }); describe('Fallback positions', () => { @@ -844,8 +752,7 @@ describe('auto-complete', () => { flush(); const position = fixture.componentInstance.trigger.nzAutocomplete.dropDownPosition; - expect(position) - .toEqual('bottom'); + expect(position).toEqual('bottom'); })); it('should reposition the panel on scroll', () => { @@ -862,19 +769,16 @@ describe('auto-complete', () => { autocomplete.dropDownPosition = 'top'; fixture.detectChanges(); - expect(autocomplete.dropDownPosition) - .toEqual('top'); + expect(autocomplete.dropDownPosition).toEqual('top'); window.scroll(0, 100); scrolledSubject.next(); fixture.detectChanges(); - expect(autocomplete.dropDownPosition) - .toEqual('bottom'); + expect(autocomplete.dropDownPosition).toEqual('bottom'); document.body.removeChild(spacer); }); - }); describe('misc', () => { @@ -893,40 +797,43 @@ describe('auto-complete', () => { }).toThrow(getNzAutocompleteMissingPanelError()); })); - it('should show the panel when the options are initialized later within a component with ' + - 'OnPush change detection', fakeAsync(() => { - fixture = TestBed.createComponent(NzTestAutocompleteWithOnPushDelayComponent); - fixture.detectChanges(); - - dispatchFakeEvent(fixture.debugElement.query(By.css('input')).nativeElement, 'focusin'); - fixture.detectChanges(); - tick(1000); - - fixture.detectChanges(); - tick(); + it( + 'should show the panel when the options are initialized later within a component with ' + + 'OnPush change detection', + fakeAsync(() => { + fixture = TestBed.createComponent(NzTestAutocompleteWithOnPushDelayComponent); + fixture.detectChanges(); - Promise.resolve().then(() => { + dispatchFakeEvent(fixture.debugElement.query(By.css('input')).nativeElement, 'focusin'); fixture.detectChanges(); - flush(); - const panel = overlayContainerElement.querySelector('.ant-select-dropdown') as HTMLElement; - expect(panel.classList).not.toContain('ant-select-dropdown-hidden'); - }); - })); + tick(1000); + fixture.detectChanges(); + tick(); + + Promise.resolve().then(() => { + fixture.detectChanges(); + flush(); + const panel = overlayContainerElement.querySelector('.ant-select-dropdown') as HTMLElement; + expect(panel.classList).not.toContain('ant-select-dropdown-hidden'); + }); + }) + ); }); - }); @Component({ template: ` -
- +
+ - {{option}} + {{ option }}
` @@ -952,12 +859,19 @@ class NzTestSimpleAutocompleteComponent { @Component({ template: ` -
- - +
+ + -
+
` }) class NzTestAutocompletePropertyComponent { @@ -969,13 +883,13 @@ class NzTestAutocompletePropertyComponent { @ViewChild(NzAutocompleteComponent) panel: NzAutocompleteComponent; @ViewChild(NzAutocompleteTriggerDirective) trigger: NzAutocompleteTriggerDirective; - constructor() { - } - + constructor() {} } @Component({ - template: `` + template: ` + + ` }) class NzTestAutocompleteWithoutPanelComponent { @ViewChild(NzAutocompleteTriggerDirective) trigger: NzAutocompleteTriggerDirective; @@ -984,11 +898,10 @@ class NzTestAutocompleteWithoutPanelComponent { @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` -
- - - -
+
+ + +
` }) class NzTestAutocompleteWithOnPushDelayComponent implements OnInit { @@ -1004,60 +917,73 @@ class NzTestAutocompleteWithOnPushDelayComponent implements OnInit { @Component({ template: ` - - - - - {{group.title}} - 更多 - - - - {{option.title}} - {{option.count}} 人 关注 - - - -` + + + + + {{ group.title }} + 更多 + + + + {{ option.title }} + {{ option.count }} 人 关注 + + + + ` }) class NzTestAutocompleteGroupComponent { inputValue: string; - optionGroups = [{ - title: '话题', - children: [{ - title: 'AntDesign one', - count: 10000 - }, { - title: 'AntDesign two', - count: 10600 - }] - }, { - title: '问题', - children: [{ - title: 'AntDesign three', - count: 60100 - }, { - title: 'AntDesign four', - count: 30010 - }] - }, { - title: '文章', - children: [{ - title: 'AntDesign five', - disabled: true, - count: 100000 - }] - }]; + optionGroups = [ + { + title: '话题', + children: [ + { + title: 'AntDesign one', + count: 10000 + }, + { + title: 'AntDesign two', + count: 10600 + } + ] + }, + { + title: '问题', + children: [ + { + title: 'AntDesign three', + count: 60100 + }, + { + title: 'AntDesign four', + count: 30010 + } + ] + }, + { + title: '文章', + children: [ + { + title: 'AntDesign five', + disabled: true, + count: 100000 + } + ] + } + ]; @ViewChild(NzAutocompleteTriggerDirective) trigger: NzAutocompleteTriggerDirective; } @Component({ template: ` -
- + + - {{option}} + {{ option }}
` diff --git a/components/avatar/avatar.spec.ts b/components/avatar/avatar.spec.ts index 83ccd33ee37..50682cd960f 100644 --- a/components/avatar/avatar.spec.ts +++ b/components/avatar/avatar.spec.ts @@ -9,8 +9,12 @@ import { NzAvatarModule } from './nz-avatar.module'; function getType(dl: DebugElement): string { const el = dl.nativeElement as HTMLElement; - if (el.querySelector('img') != null) { return 'image'; } - if (el.querySelector('.anticon') != null) { return 'icon'; } + if (el.querySelector('img') != null) { + return 'image'; + } + if (el.querySelector('.anticon') != null) { + return 'icon'; + } return el.innerText.trim().length === 0 ? '' : 'text'; } @@ -20,8 +24,8 @@ describe('avatar', () => { let dl: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ - imports: [ NzAvatarModule, NzIconTestModule ], - declarations: [ TestAvatarComponent ] + imports: [NzAvatarModule, NzIconTestModule], + declarations: [TestAvatarComponent] }).compileComponents(); fixture = TestBed.createComponent(TestAvatarComponent); context = fixture.componentInstance; @@ -43,7 +47,8 @@ describe('avatar', () => { fixture.detectChanges(); expect(getType(dl)).toBe('icon'); expect(context.comp.hasSrc).toBe(false); - context.nzSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=='; + context.nzSrc = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=='; tick(); fixture.detectChanges(); expect(context.comp.hasSrc).toBe(true); @@ -89,7 +94,7 @@ describe('avatar', () => { }); describe('#nzShape', () => { - for (const type of [ 'square', 'circle' ]) { + for (const type of ['square', 'circle']) { it(type, () => { context.nzShape = type; fixture.detectChanges(); @@ -99,7 +104,7 @@ describe('avatar', () => { }); describe('#nzSize', () => { - for (const item of [ { size: 'large', cls: 'lg'}, { size: 'small', cls: 'sm'} ]) { + for (const item of [{ size: 'large', cls: 'lg' }, { size: 'small', cls: 'sm' }]) { it(item.size, () => { context.nzSize = item.size; fixture.detectChanges(); @@ -123,7 +128,6 @@ describe('avatar', () => { fixture.detectChanges(); expect(hostStyle.fontSize === `${context.nzSize / 2}px`).toBe(true); }); - }); describe('order: image > icon > text', () => { @@ -161,14 +165,16 @@ describe('avatar', () => { @Component({ template: ` - + `, - styleUrls: [ './style/index.less' ] + styleUrls: ['./style/index.less'] }) class TestAvatarComponent { @ViewChild('comp') comp: NzAvatarComponent; @@ -176,5 +182,7 @@ class TestAvatarComponent { nzSize: string | number = 'large'; nzIcon: string | null = 'anticon anticon-user'; nzText: string | null = 'A'; - nzSrc: string | null = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==`; + nzSrc: + | string + | null = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==`; } diff --git a/components/avatar/demo/badge.ts b/components/avatar/demo/badge.ts index bf3e46aeefd..357f42f3015 100644 --- a/components/avatar/demo/badge.ts +++ b/components/avatar/demo/badge.ts @@ -3,12 +3,12 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-avatar-badge', template: ` - - - - - - + + + + + + ` }) -export class NzDemoAvatarBadgeComponent { } +export class NzDemoAvatarBadgeComponent {} diff --git a/components/avatar/demo/basic.ts b/components/avatar/demo/basic.ts index f60ebb8f66a..7da2d2b67bc 100644 --- a/components/avatar/demo/basic.ts +++ b/components/avatar/demo/basic.ts @@ -3,24 +3,26 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-avatar-basic', template: ` -
- - - - -
-
- - - - -
+
+ + + + +
+
+ + + + +
`, - styles: [` - nz-avatar { - margin-top: 16px; - margin-right: 16px; - } - `] + styles: [ + ` + nz-avatar { + margin-top: 16px; + margin-right: 16px; + } + ` + ] }) -export class NzDemoAvatarBasicComponent { } +export class NzDemoAvatarBasicComponent {} diff --git a/components/avatar/demo/dynamic.ts b/components/avatar/demo/dynamic.ts index 73a18320f28..5cbc8683732 100644 --- a/components/avatar/demo/dynamic.ts +++ b/components/avatar/demo/dynamic.ts @@ -1,27 +1,32 @@ import { Component } from '@angular/core'; -const userList = [ 'U', 'Lucy', 'Tom', 'Edward' ]; -const colorList = [ '#f56a00', '#7265e6', '#ffbf00', '#00a2ae' ]; +const userList = ['U', 'Lucy', 'Tom', 'Edward']; +const colorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae']; @Component({ selector: 'nz-demo-avatar-dynamic', template: ` - + `, - styles : [] + styles: [] }) export class NzDemoAvatarDynamicComponent { - text: string = userList[ 3 ]; - color: string = colorList[ 3 ]; + text: string = userList[3]; + color: string = colorList[3]; change(): void { let idx = userList.indexOf(this.text); ++idx; if (idx === userList.length) idx = 0; - this.text = userList[ idx ]; - this.color = colorList[ idx ]; + this.text = userList[idx]; + this.color = colorList[idx]; } } diff --git a/components/avatar/demo/type.ts b/components/avatar/demo/type.ts index 010d0518fe6..21af2a1c796 100644 --- a/components/avatar/demo/type.ts +++ b/components/avatar/demo/type.ts @@ -3,18 +3,20 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-avatar-type', template: ` - - - - - - + + + + + + `, - styles: [` - nz-avatar { - margin-top: 16px; - margin-right: 16px; - } - `] + styles: [ + ` + nz-avatar { + margin-top: 16px; + margin-right: 16px; + } + ` + ] }) -export class NzDemoAvatarTypeComponent { } +export class NzDemoAvatarTypeComponent {} diff --git a/components/avatar/nz-avatar.component.ts b/components/avatar/nz-avatar.component.ts index 31826abdcb1..632dbf9d8b9 100644 --- a/components/avatar/nz-avatar.component.ts +++ b/components/avatar/nz-avatar.component.ts @@ -18,20 +18,18 @@ export type NzAvatarShape = 'square' | 'circle'; export type NzAvatarSize = NzSizeLDSType | number; export interface NzAvatarSizeMap { - [ size: string ]: string; + [size: string]: string; } @Component({ - selector : 'nz-avatar', - templateUrl : './nz-avatar.component.html', - providers : [ NzUpdateHostClassService ], + selector: 'nz-avatar', + templateUrl: './nz-avatar.component.html', + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None - + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None }) export class NzAvatarComponent implements OnChanges { - @Input() nzShape: NzAvatarShape = 'circle'; @Input() nzSize: NzAvatarSize = 'default'; @Input() nzText: string; @@ -54,16 +52,16 @@ export class NzAvatarComponent implements OnChanges { private elementRef: ElementRef, private cd: ChangeDetectorRef, private updateHostClassService: NzUpdateHostClassService, - private renderer: Renderer2) { - } + private renderer: Renderer2 + ) {} setClass(): this { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-${this.sizeMap[ this.nzSize ]}` ]: this.sizeMap[ this.nzSize ], - [ `${this.prefixCls}-${this.nzShape}` ] : this.nzShape, - [ `${this.prefixCls}-icon` ] : this.nzIcon, - [ `${this.prefixCls}-image` ] : this.hasSrc // downgrade after image error + [this.prefixCls]: true, + [`${this.prefixCls}-${this.sizeMap[this.nzSize]}`]: this.sizeMap[this.nzSize], + [`${this.prefixCls}-${this.nzShape}`]: this.nzShape, + [`${this.prefixCls}-icon`]: this.nzIcon, + [`${this.prefixCls}-image`]: this.hasSrc // downgrade after image error }; this.updateHostClassService.updateHostClass(this.el, classMap); this.cd.detectChanges(); diff --git a/components/avatar/nz-avatar.module.ts b/components/avatar/nz-avatar.module.ts index 14aea5927ce..e65eff83609 100644 --- a/components/avatar/nz-avatar.module.ts +++ b/components/avatar/nz-avatar.module.ts @@ -5,9 +5,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzAvatarComponent } from './nz-avatar.component'; @NgModule({ - declarations: [ NzAvatarComponent ], - exports : [ NzAvatarComponent ], - imports : [ CommonModule, NzIconModule ] + declarations: [NzAvatarComponent], + exports: [NzAvatarComponent], + imports: [CommonModule, NzIconModule] }) -export class NzAvatarModule { -} +export class NzAvatarModule {} diff --git a/components/back-top/back-top.spec.ts b/components/back-top/back-top.spec.ts index c87825d4fc2..6a30a456fcc 100644 --- a/components/back-top/back-top.spec.ts +++ b/components/back-top/back-top.spec.ts @@ -1,14 +1,5 @@ -import { - Component, - DebugElement, - ViewChild -} from '@angular/core'; -import { - fakeAsync, - tick, - ComponentFixture, - TestBed -} from '@angular/core/testing'; +import { Component, DebugElement, ViewChild } from '@angular/core'; +import { fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; @@ -42,10 +33,7 @@ describe('Component:nz-back-top', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ - NzBackTopModule, - NoopAnimationsModule - ], + imports: [NzBackTopModule, NoopAnimationsModule], declarations: [TestBackTopComponent, TestBackTopTemplateComponent], providers: [ { @@ -209,9 +197,9 @@ describe('Component:nz-back-top', () => { @Component({ template: ` - -
-` + +
+ ` }) class TestBackTopComponent { @ViewChild(NzBackTopComponent) @@ -221,12 +209,12 @@ class TestBackTopComponent { @Component({ template: ` my comp - - -
-
-
-` + + +
+
+
+ ` }) class TestBackTopTemplateComponent { @ViewChild(NzBackTopComponent) @@ -240,10 +228,7 @@ class MockNzScrollService { return this.mockTopOffset; } - scrollTo( - _containerEl: Element | Window, - targetTopValue: number = 0 - ): void { + scrollTo(_containerEl: Element | Window, targetTopValue: number = 0): void { this.mockTopOffset = targetTopValue; } } diff --git a/components/back-top/demo/basic.ts b/components/back-top/demo/basic.ts index 78eb49468bc..418f7d983da 100644 --- a/components/back-top/demo/basic.ts +++ b/components/back-top/demo/basic.ts @@ -8,11 +8,12 @@ import { Component } from '@angular/core'; gray button. `, - styles : [ ` - strong { - color: rgba(64, 64, 64, 0.6); - } - ` ] + styles: [ + ` + strong { + color: rgba(64, 64, 64, 0.6); + } + ` + ] }) -export class NzDemoBackTopBasicComponent { -} +export class NzDemoBackTopBasicComponent {} diff --git a/components/back-top/demo/custom.ts b/components/back-top/demo/custom.ts index bf303084b37..fa3cc78b903 100644 --- a/components/back-top/demo/custom.ts +++ b/components/back-top/demo/custom.ts @@ -12,26 +12,28 @@ import { Component } from '@angular/core'; blue button. `, - styles : [ ` - :host ::ng-deep .ant-back-top { - bottom: 100px; - } + styles: [ + ` + :host ::ng-deep .ant-back-top { + bottom: 100px; + } - :host ::ng-deep .ant-back-top-inner { - height: 40px; - width: 40px; - line-height: 40px; - border-radius: 4px; - background-color: #1088e9; - color: #fff; - text-align: center; - font-size: 20px; - } + :host ::ng-deep .ant-back-top-inner { + height: 40px; + width: 40px; + line-height: 40px; + border-radius: 4px; + background-color: #1088e9; + color: #fff; + text-align: center; + font-size: 20px; + } - :host ::ng-deep strong { - color: #1088e9; - } - ` ] + :host ::ng-deep strong { + color: #1088e9; + } + ` + ] }) export class NzDemoBackTopCustomComponent { notify(): void { diff --git a/components/back-top/demo/target.ts b/components/back-top/demo/target.ts index 9d5d92f3564..5dab5b329bd 100644 --- a/components/back-top/demo/target.ts +++ b/components/back-top/demo/target.ts @@ -11,25 +11,26 @@ import { Component } from '@angular/core';
`, - styles : [ ` - :host ::ng-deep .long-div { - height: 300px; - overflow-y: scroll; - background-image: url(//zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg); - } + styles: [ + ` + :host ::ng-deep .long-div { + height: 300px; + overflow-y: scroll; + background-image: url(//zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg); + } - :host ::ng-deep .long-div-inner { - height: 1500px; - } + :host ::ng-deep .long-div-inner { + height: 1500px; + } - :host ::ng-deep .long-div .ant-back-top { - right: 150px; - } + :host ::ng-deep .long-div .ant-back-top { + right: 150px; + } - :host ::ng-deep strong { - color: rgba(64, 64, 64, 0.6); - } - ` ] + :host ::ng-deep strong { + color: rgba(64, 64, 64, 0.6); + } + ` + ] }) -export class NzDemoBackTopTargetComponent { -} +export class NzDemoBackTopTargetComponent {} diff --git a/components/back-top/nz-back-top.component.ts b/components/back-top/nz-back-top.component.ts index f8c4e4c9227..8cc1438675b 100644 --- a/components/back-top/nz-back-top.component.ts +++ b/components/back-top/nz-back-top.component.ts @@ -21,15 +21,14 @@ import { NzScrollService } from '../core/scroll/nz-scroll.service'; import { toNumber } from '../core/util/convert'; @Component({ - selector : 'nz-back-top', - animations : [ fadeMotion ], - templateUrl : './nz-back-top.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: 'nz-back-top', + animations: [fadeMotion], + templateUrl: './nz-back-top.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false }) export class NzBackTopComponent implements OnInit, OnDestroy { - private scroll$: Subscription | null = null; private target: HTMLElement | null = null; @@ -57,8 +56,7 @@ export class NzBackTopComponent implements OnInit, OnDestroy { @Output() readonly nzClick: EventEmitter = new EventEmitter(); // tslint:disable-next-line:no-any - constructor(private scrollSrv: NzScrollService, @Inject(DOCUMENT) private doc: any, private cd: ChangeDetectorRef) { - } + constructor(private scrollSrv: NzScrollService, @Inject(DOCUMENT) private doc: any, private cd: ChangeDetectorRef) {} ngOnInit(): void { if (!this.scroll$) { @@ -92,14 +90,15 @@ export class NzBackTopComponent implements OnInit, OnDestroy { private registerScrollEvent(): void { this.removeListen(); this.handleScroll(); - this.scroll$ = fromEvent(this.getTarget(), 'scroll').pipe( - throttleTime(50), - distinctUntilChanged() - ).subscribe(() => this.handleScroll()); + this.scroll$ = fromEvent(this.getTarget(), 'scroll') + .pipe( + throttleTime(50), + distinctUntilChanged() + ) + .subscribe(() => this.handleScroll()); } ngOnDestroy(): void { this.removeListen(); } - } diff --git a/components/back-top/nz-back-top.module.ts b/components/back-top/nz-back-top.module.ts index 7e22b3a825a..fab86d2e555 100644 --- a/components/back-top/nz-back-top.module.ts +++ b/components/back-top/nz-back-top.module.ts @@ -6,10 +6,9 @@ import { SCROLL_SERVICE_PROVIDER } from '../core/scroll/nz-scroll.service'; import { NzBackTopComponent } from './nz-back-top.component'; @NgModule({ - declarations: [ NzBackTopComponent ], - exports : [ NzBackTopComponent ], - imports : [ CommonModule ], - providers : [ SCROLL_SERVICE_PROVIDER ] + declarations: [NzBackTopComponent], + exports: [NzBackTopComponent], + imports: [CommonModule], + providers: [SCROLL_SERVICE_PROVIDER] }) -export class NzBackTopModule { -} +export class NzBackTopModule {} diff --git a/components/badge/demo/basic.ts b/components/badge/demo/basic.ts index 1ffc66c6698..edebd93122a 100644 --- a/components/badge/demo/basic.ts +++ b/components/badge/demo/basic.ts @@ -16,20 +16,21 @@ import { Component } from '@angular/core'; `, - styles : [ ` - nz-badge { - margin-right: 20px; - } + styles: [ + ` + nz-badge { + margin-right: 20px; + } - .head-example { - width: 42px; - height: 42px; - border-radius: 4px; - background: #eee; - display: inline-block; - vertical-align: middle; - } - ` ] + .head-example { + width: 42px; + height: 42px; + border-radius: 4px; + background: #eee; + display: inline-block; + vertical-align: middle; + } + ` + ] }) -export class NzDemoBadgeBasicComponent { -} +export class NzDemoBadgeBasicComponent {} diff --git a/components/badge/demo/change.ts b/components/badge/demo/change.ts index 67909bdc35c..1b0626a8197 100644 --- a/components/badge/demo/change.ts +++ b/components/badge/demo/change.ts @@ -1,8 +1,8 @@ import { Component } from '@angular/core'; @Component({ - selector : 'nz-demo-badge-change', - template : ` + selector: 'nz-demo-badge-change', + template: `
@@ -20,23 +20,24 @@ import { Component } from '@angular/core';
`, - styles : [ ` - nz-badge { - margin-right: 20px; - } + styles: [ + ` + nz-badge { + margin-right: 20px; + } - .head-example { - width: 42px; - height: 42px; - border-radius: 4px; - background: #eee; - display: inline-block; - vertical-align: middle; - } - ` ] + .head-example { + width: 42px; + height: 42px; + border-radius: 4px; + background: #eee; + display: inline-block; + vertical-align: middle; + } + ` + ] }) export class NzDemoBadgeChangeComponent { - count = 5; dot = true; diff --git a/components/badge/demo/dot.ts b/components/badge/demo/dot.ts index 87870f1fd8c..7bef33aba46 100644 --- a/components/badge/demo/dot.ts +++ b/components/badge/demo/dot.ts @@ -9,8 +9,8 @@ import { Component } from '@angular/core'; Link something `, - styles : [ - ` + styles: [ + ` nz-badge { margin-right: 20px; } @@ -20,8 +20,8 @@ import { Component } from '@angular/core'; height: 16px; line-height: 16px; font-size: 16px; - }` + } + ` ] }) -export class NzDemoBadgeDotComponent { -} +export class NzDemoBadgeDotComponent {} diff --git a/components/badge/demo/link.ts b/components/badge/demo/link.ts index 489f09fd252..988867b842e 100644 --- a/components/badge/demo/link.ts +++ b/components/badge/demo/link.ts @@ -9,16 +9,17 @@ import { Component } from '@angular/core'; `, - styles : [ ` - .head-example { - width: 42px; - height: 42px; - border-radius: 4px; - background: #eee; - display: inline-block; - vertical-align: middle; - } - ` ] + styles: [ + ` + .head-example { + width: 42px; + height: 42px; + border-radius: 4px; + background: #eee; + display: inline-block; + vertical-align: middle; + } + ` + ] }) -export class NzDemoBadgeLinkComponent { -} +export class NzDemoBadgeLinkComponent {} diff --git a/components/badge/demo/no-wrapper.ts b/components/badge/demo/no-wrapper.ts index f61042afb4e..d2e344f3567 100644 --- a/components/badge/demo/no-wrapper.ts +++ b/components/badge/demo/no-wrapper.ts @@ -4,14 +4,18 @@ import { Component } from '@angular/core'; selector: 'nz-demo-badge-no-wrapper', template: ` - + `, - styles : [ ` - nz-badge { - margin-right: 20px; - } - ` ] + styles: [ + ` + nz-badge { + margin-right: 20px; + } + ` + ] }) -export class NzDemoBadgeNoWrapperComponent { -} +export class NzDemoBadgeNoWrapperComponent {} diff --git a/components/badge/demo/overflow.ts b/components/badge/demo/overflow.ts index 78915412830..8cc7fc6cf5b 100644 --- a/components/badge/demo/overflow.ts +++ b/components/badge/demo/overflow.ts @@ -16,20 +16,21 @@ import { Component } from '@angular/core'; `, - styles : [ ` - nz-badge { - margin-right: 20px; - } + styles: [ + ` + nz-badge { + margin-right: 20px; + } - .head-example { - width: 42px; - height: 42px; - border-radius: 4px; - background: #eee; - display: inline-block; - vertical-align: middle; - } - ` ] + .head-example { + width: 42px; + height: 42px; + border-radius: 4px; + background: #eee; + display: inline-block; + vertical-align: middle; + } + ` + ] }) -export class NzDemoBadgeOverflowComponent { -} +export class NzDemoBadgeOverflowComponent {} diff --git a/components/badge/demo/status.ts b/components/badge/demo/status.ts index 92780c1ccfb..e38c829b025 100644 --- a/components/badge/demo/status.ts +++ b/components/badge/demo/status.ts @@ -8,20 +8,19 @@ import { Component } from '@angular/core'; - -
+ +
-
+
-
+
-
+
-
+
-
- +
+ ` }) -export class NzDemoBadgeStatusComponent { -} +export class NzDemoBadgeStatusComponent {} diff --git a/components/badge/nz-badge.component.ts b/components/badge/nz-badge.component.ts index 897ccd48a43..3206103dcd6 100644 --- a/components/badge/nz-badge.component.ts +++ b/components/badge/nz-badge.component.ts @@ -3,9 +3,12 @@ import { ChangeDetectionStrategy, Component, ElementRef, - Input, OnChanges, + Input, + OnChanges, OnInit, - Renderer2, SimpleChanges, TemplateRef, + Renderer2, + SimpleChanges, + TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; @@ -16,20 +19,20 @@ import { InputBoolean } from '../core/util/convert'; export type NzBadgeStatusType = 'success' | 'processing' | 'default' | 'error' | 'warning'; @Component({ - selector : 'nz-badge', + selector: 'nz-badge', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - animations : [ zoomBadgeMotion ], - templateUrl : './nz-badge.component.html', - host : { + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + animations: [zoomBadgeMotion], + templateUrl: './nz-badge.component.html', + host: { '[class.ant-badge-status]': 'nzStatus' } }) export class NzBadgeComponent implements OnInit, AfterViewInit, OnChanges { maxNumberArray: string[] = []; countArray: number[] = []; - countSingleArray = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; + countSingleArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; count: number; @ViewChild('contentElement') contentElement: ElementRef; @Input() @InputBoolean() nzShowZero = false; @@ -37,7 +40,7 @@ export class NzBadgeComponent implements OnInit, AfterViewInit, OnChanges { @Input() @InputBoolean() nzDot = false; @Input() nzOverflowCount = 99; @Input() nzText: string; - @Input() nzStyle: { [ key: string ]: string }; + @Input() nzStyle: { [key: string]: string }; @Input() nzStatus: NzBadgeStatusType; @Input() nzCount: number | TemplateRef; @@ -73,7 +76,10 @@ export class NzBadgeComponent implements OnInit, AfterViewInit, OnChanges { const { nzOverflowCount, nzCount } = changes; if (nzCount && !(nzCount.currentValue instanceof TemplateRef)) { this.count = Math.max(0, nzCount.currentValue); - this.countArray = this.count.toString().split('').map(item => +item); + this.countArray = this.count + .toString() + .split('') + .map(item => +item); } if (nzOverflowCount) { this.generateMaxNumberArray(); diff --git a/components/badge/nz-badge.module.ts b/components/badge/nz-badge.module.ts index 29d9b4eaa12..09a4d014603 100644 --- a/components/badge/nz-badge.module.ts +++ b/components/badge/nz-badge.module.ts @@ -6,9 +6,8 @@ import { NzAddOnModule } from '../core/addon/addon.module'; import { NzBadgeComponent } from './nz-badge.component'; @NgModule({ - declarations: [ NzBadgeComponent ], - exports : [ NzBadgeComponent ], - imports : [ CommonModule, ObserversModule, NzAddOnModule ] + declarations: [NzBadgeComponent], + exports: [NzBadgeComponent], + imports: [CommonModule, ObserversModule, NzAddOnModule] }) -export class NzBadgeModule { -} +export class NzBadgeModule {} diff --git a/components/badge/nz-badge.spec.ts b/components/badge/nz-badge.spec.ts index 0c8eb4ef8eb..e60903bac77 100644 --- a/components/badge/nz-badge.spec.ts +++ b/components/badge/nz-badge.spec.ts @@ -11,8 +11,8 @@ import { NzBadgeModule } from './nz-badge.module'; describe('badge', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzBadgeModule, NoopAnimationsModule ], - declarations: [ NzTestBadgeBasicComponent ] + imports: [NzBadgeModule, NoopAnimationsModule], + declarations: [NzTestBadgeBasicComponent] }); TestBed.compileComponents(); })); @@ -43,8 +43,8 @@ describe('badge', () => { testComponent.count = 10; fixture.detectChanges(); expect(badgeElement.nativeElement.querySelector('sup').classList).toContain('ant-badge-multiple-words'); - expect(badgeElement.nativeElement.querySelectorAll('.current')[ 0 ].innerText).toBe('1'); - expect(badgeElement.nativeElement.querySelectorAll('.current')[ 1 ].innerText).toBe('0'); + expect(badgeElement.nativeElement.querySelectorAll('.current')[0].innerText).toBe('1'); + expect(badgeElement.nativeElement.querySelectorAll('.current')[1].innerText).toBe('0'); }); it('should overflow work', () => { @@ -98,18 +98,20 @@ describe('badge', () => { tick(1000); fixture.detectChanges(); badgeElement = fixture.debugElement.query(By.directive(NzBadgeComponent)); -// TODO: fix next line error -// expect(badgeElement.nativeElement.classList).toContain('ant-badge-not-a-wrapper'); + // TODO: fix next line error + // expect(badgeElement.nativeElement.classList).toContain('ant-badge-not-a-wrapper'); expect(badgeElement.nativeElement.querySelector('sup').style.backgroundColor).toBe('rgb(82, 196, 26)'); })); it('should status work', () => { testComponent.inner = false; - const statusList = [ 'success', 'processing', 'default', 'error', 'warning' ]; + const statusList = ['success', 'processing', 'default', 'error', 'warning']; statusList.forEach(status => { testComponent.status = status; fixture.detectChanges(); - expect(badgeElement.nativeElement.querySelector('.ant-badge-status-dot').classList).toContain(`ant-badge-status-${status}`); + expect(badgeElement.nativeElement.querySelector('.ant-badge-status-dot').classList).toContain( + `ant-badge-status-${status}` + ); }); testComponent.text = 'test'; fixture.detectChanges(); @@ -128,7 +130,8 @@ describe('badge', () => { [nzShowZero]="showZero" [nzOverflowCount]="overflow" [nzStyle]="style" - [nzDot]="dot"> + [nzDot]="dot" + > ` diff --git a/components/breadcrumb/demo/basic.ts b/components/breadcrumb/demo/basic.ts index 5fb30696ff7..957b5056a0f 100644 --- a/components/breadcrumb/demo/basic.ts +++ b/components/breadcrumb/demo/basic.ts @@ -13,8 +13,8 @@ import { Component } from '@angular/core'; An Application - `, - styles : [] + + `, + styles: [] }) -export class NzDemoBreadcrumbBasicComponent { -} +export class NzDemoBreadcrumbBasicComponent {} diff --git a/components/breadcrumb/demo/router.ts b/components/breadcrumb/demo/router.ts index 80d87ab5828..8ec50d56a58 100644 --- a/components/breadcrumb/demo/router.ts +++ b/components/breadcrumb/demo/router.ts @@ -10,8 +10,8 @@ import { Component } from '@angular/core'; Breadcrumb - `, - styles : [] + + `, + styles: [] }) -export class NzDemoBreadcrumbRouterComponent { -} +export class NzDemoBreadcrumbRouterComponent {} diff --git a/components/breadcrumb/demo/separator.ts b/components/breadcrumb/demo/separator.ts index ef9f91d8d4a..f0b6f352ec4 100644 --- a/components/breadcrumb/demo/separator.ts +++ b/components/breadcrumb/demo/separator.ts @@ -15,7 +15,7 @@ import { Component } from '@angular/core'; An Application -
+

TemplateRef

@@ -30,8 +30,8 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` h4:first-child { margin-top: 0; } @@ -45,5 +45,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoBreadcrumbSeparatorComponent { -} +export class NzDemoBreadcrumbSeparatorComponent {} diff --git a/components/breadcrumb/demo/withIcon.ts b/components/breadcrumb/demo/withIcon.ts index 287579dd76d..582bffeeae4 100644 --- a/components/breadcrumb/demo/withIcon.ts +++ b/components/breadcrumb/demo/withIcon.ts @@ -13,7 +13,8 @@ import { Component } from '@angular/core'; Application - `, - styles : [] + + `, + styles: [] }) -export class NzDemoBreadcrumbWithIconComponent { } +export class NzDemoBreadcrumbWithIconComponent {} diff --git a/components/breadcrumb/nz-breadcrumb-item.component.ts b/components/breadcrumb/nz-breadcrumb-item.component.ts index 0fa2d4a49c4..ba445ea88e9 100755 --- a/components/breadcrumb/nz-breadcrumb-item.component.ts +++ b/components/breadcrumb/nz-breadcrumb-item.component.ts @@ -3,21 +3,23 @@ import { ChangeDetectionStrategy, Component, ViewEncapsulation } from '@angular/ import { NzBreadCrumbComponent } from './nz-breadcrumb.component'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-breadcrumb-item', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-breadcrumb-item', preserveWhitespaces: false, - templateUrl : 'nz-breadcrumb-item.component.html', - styles : [ ` - nz-breadcrumb-item:last-child { - color: rgba(0, 0, 0, 0.65); - } + templateUrl: 'nz-breadcrumb-item.component.html', + styles: [ + ` + nz-breadcrumb-item:last-child { + color: rgba(0, 0, 0, 0.65); + } - nz-breadcrumb-item:last-child .ant-breadcrumb-separator { - display: none; - } - ` ] + nz-breadcrumb-item:last-child .ant-breadcrumb-separator { + display: none; + } + ` + ] }) export class NzBreadCrumbItemComponent { - constructor(public nzBreadCrumbComponent: NzBreadCrumbComponent) { } + constructor(public nzBreadCrumbComponent: NzBreadCrumbComponent) {} } diff --git a/components/breadcrumb/nz-breadcrumb.component.ts b/components/breadcrumb/nz-breadcrumb.component.ts index 60da1f24705..1645a23546e 100755 --- a/components/breadcrumb/nz-breadcrumb.component.ts +++ b/components/breadcrumb/nz-breadcrumb.component.ts @@ -1,12 +1,14 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, + Component, + ElementRef, Injector, Input, NgZone, OnDestroy, - OnInit, Renderer2, + OnInit, + Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -23,16 +25,18 @@ export interface BreadcrumbOption { } @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-breadcrumb', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-breadcrumb', preserveWhitespaces: false, - templateUrl : './nz-breadcrumb.component.html', - styles : [ ` - nz-breadcrumb { - display: block; - } - ` ] + templateUrl: './nz-breadcrumb.component.html', + styles: [ + ` + nz-breadcrumb { + display: block; + } + ` + ] }) export class NzBreadCrumbComponent implements OnInit, OnDestroy { @Input() nzAutoGenerate = false; @@ -42,7 +46,13 @@ export class NzBreadCrumbComponent implements OnInit, OnDestroy { private destroy$ = new Subject(); - constructor(private injector: Injector, private ngZone: NgZone, private cd: ChangeDetectorRef, elementRef: ElementRef, renderer: Renderer2) { + constructor( + private injector: Injector, + private ngZone: NgZone, + private cd: ChangeDetectorRef, + elementRef: ElementRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-breadcrumb'); } @@ -51,10 +61,15 @@ export class NzBreadCrumbComponent implements OnInit, OnDestroy { try { const activatedRoute = this.injector.get(ActivatedRoute); const router = this.injector.get(Router); - router.events.pipe(filter(e => e instanceof NavigationEnd), takeUntil(this.destroy$)).subscribe(() => { - this.breadcrumbs = this.getBreadcrumbs(activatedRoute.root); - this.cd.markForCheck(); - }); + router.events + .pipe( + filter(e => e instanceof NavigationEnd), + takeUntil(this.destroy$) + ) + .subscribe(() => { + this.breadcrumbs = this.getBreadcrumbs(activatedRoute.root); + this.cd.markForCheck(); + }); } catch (e) { throw new Error('[NG-ZORRO] You should import RouterModule if you want to use NzAutoGenerate'); } @@ -68,10 +83,21 @@ export class NzBreadCrumbComponent implements OnInit, OnDestroy { navigate(url: string, e: MouseEvent): void { e.preventDefault(); - this.ngZone.run(() => this.injector.get(Router).navigateByUrl(url).then()).then(); + this.ngZone + .run(() => + this.injector + .get(Router) + .navigateByUrl(url) + .then() + ) + .then(); } - private getBreadcrumbs(route: ActivatedRoute, url: string = '', breadcrumbs: BreadcrumbOption[] = []): BreadcrumbOption[] | undefined { + private getBreadcrumbs( + route: ActivatedRoute, + url: string = '', + breadcrumbs: BreadcrumbOption[] = [] + ): BreadcrumbOption[] | undefined { const children: ActivatedRoute[] = route.children; // If there's no sub root, then stop the recurse and returns the generated breadcrumbs. if (children.length === 0) { @@ -86,9 +112,9 @@ export class NzBreadCrumbComponent implements OnInit, OnDestroy { // If have data, go to generate a breadcrumb for it. if (child.snapshot.data.hasOwnProperty(NZ_ROUTE_DATA_BREADCRUMB)) { const breadcrumb: BreadcrumbOption = { - label : child.snapshot.data[ NZ_ROUTE_DATA_BREADCRUMB ] || 'Breadcrumb', + label: child.snapshot.data[NZ_ROUTE_DATA_BREADCRUMB] || 'Breadcrumb', params: child.snapshot.params, - url : nextUrl + url: nextUrl }; breadcrumbs.push(breadcrumb); } diff --git a/components/breadcrumb/nz-breadcrumb.module.ts b/components/breadcrumb/nz-breadcrumb.module.ts index f937e7145cb..f0847c5d716 100644 --- a/components/breadcrumb/nz-breadcrumb.module.ts +++ b/components/breadcrumb/nz-breadcrumb.module.ts @@ -7,8 +7,8 @@ import { NzBreadCrumbItemComponent } from './nz-breadcrumb-item.component'; import { NzBreadCrumbComponent } from './nz-breadcrumb.component'; @NgModule({ - imports : [ CommonModule, NzAddOnModule ], - declarations: [ NzBreadCrumbComponent, NzBreadCrumbItemComponent ], - exports : [ NzBreadCrumbComponent, NzBreadCrumbItemComponent ] + imports: [CommonModule, NzAddOnModule], + declarations: [NzBreadCrumbComponent, NzBreadCrumbItemComponent], + exports: [NzBreadCrumbComponent, NzBreadCrumbItemComponent] }) export class NzBreadCrumbModule {} diff --git a/components/breadcrumb/nz-breadcrumb.spec.ts b/components/breadcrumb/nz-breadcrumb.spec.ts index bc2a095ed90..6f26b28d106 100644 --- a/components/breadcrumb/nz-breadcrumb.spec.ts +++ b/components/breadcrumb/nz-breadcrumb.spec.ts @@ -22,9 +22,9 @@ describe('breadcrumb', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzBreadCrumbModule ], - declarations: [ NzDemoBreadcrumbBasicComponent ], - providers : [] + imports: [NzBreadCrumbModule], + declarations: [NzDemoBreadcrumbBasicComponent], + providers: [] }).compileComponents(); })); @@ -36,8 +36,12 @@ describe('breadcrumb', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-breadcrumb-link'))).toBe(true); - expect(items.every(item => item.nativeElement.children[ 1 ].classList.contains('ant-breadcrumb-separator'))).toBe(true); + expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-breadcrumb-link'))).toBe( + true + ); + expect(items.every(item => item.nativeElement.children[1].classList.contains('ant-breadcrumb-separator'))).toBe( + true + ); expect(breadcrumb.nativeElement.classList.contains('ant-breadcrumb')).toBe(true); }); }); @@ -49,8 +53,8 @@ describe('breadcrumb', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzBreadCrumbModule, NzIconTestModule ], - declarations: [ NzDemoBreadcrumbSeparatorComponent ] + imports: [NzBreadCrumbModule, NzIconTestModule], + declarations: [NzDemoBreadcrumbSeparatorComponent] }).compileComponents(); })); @@ -62,11 +66,17 @@ describe('breadcrumb', () => { it('should nzSeparator work', () => { fixture.detectChanges(); - expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-breadcrumb-link'))).toBe(true); - expect(items.every(item => item.nativeElement.children[ 1 ].classList.contains('ant-breadcrumb-separator'))).toBe(true); + expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-breadcrumb-link'))).toBe( + true + ); + expect(items.every(item => item.nativeElement.children[1].classList.contains('ant-breadcrumb-separator'))).toBe( + true + ); expect(breadcrumbs.every(breadcrumb => breadcrumb.nativeElement.classList.contains('ant-breadcrumb'))).toBe(true); - expect(items[ 0 ].nativeElement.children[ 1 ].innerText.indexOf('>') > -1).toBe(true); - expect(items[ 3 ].nativeElement.children[ 1 ].firstElementChild!.classList.contains('anticon-arrow-right')).toBe(true); + expect(items[0].nativeElement.children[1].innerText.indexOf('>') > -1).toBe(true); + expect(items[3].nativeElement.children[1].firstElementChild!.classList.contains('anticon-arrow-right')).toBe( + true + ); }); }); @@ -79,8 +89,8 @@ describe('breadcrumb', () => { // TODO: pending this test because of Angular's bug: https://github.com/angular/angular/issues/25837 xit('should auto generating work', fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzBreadCrumbModule, RouterTestingModule.withRoutes(routes) ], - declarations: [ NzBreadcrumbAutoGenerateDemoComponent, NzBreadcrumbNullComponent ] + imports: [CommonModule, NzBreadCrumbModule, RouterTestingModule.withRoutes(routes)], + declarations: [NzBreadcrumbAutoGenerateDemoComponent, NzBreadcrumbNullComponent] }).compileComponents(); fixture = TestBed.createComponent(NzBreadcrumbAutoGenerateDemoComponent); breadcrumb = fixture.debugElement.query(By.directive(NzBreadCrumbComponent)); @@ -89,25 +99,25 @@ describe('breadcrumb', () => { router = TestBed.get(Router); router.initialNavigation(); // Generate breadcrumb items. - router.navigate([ 'one', 'two', 'three', 'four' ]); + router.navigate(['one', 'two', 'three', 'four']); fixture.detectChanges(); flush(); fixture.detectChanges(); items = fixture.debugElement.queryAll(By.directive(NzBreadCrumbItemComponent)); // Should generate 2 breadcrumbs when reaching out of the `data` scope. expect(breadcrumb.componentInstance.breadcrumbs.length).toBe(2); - dispatchMouseEvent(items[ 1 ].nativeElement.querySelector('a'), 'click'); - router.navigate([ 'one', 'two', 'three' ]); + dispatchMouseEvent(items[1].nativeElement.querySelector('a'), 'click'); + router.navigate(['one', 'two', 'three']); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(breadcrumb.componentInstance.breadcrumbs.length).toBe(2); - router.navigate([ 'one', 'two' ]); + router.navigate(['one', 'two']); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(breadcrumb.componentInstance.breadcrumbs.length).toBe(1); - router.navigate([ 'one' ]); + router.navigate(['one']); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -118,8 +128,8 @@ describe('breadcrumb', () => { it('should raise error when RouterModule is not included', fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzBreadCrumbModule ], // no RouterTestingModule - declarations: [ NzBreadcrumbAutoGenerateErrorDemoComponent ] + imports: [NzBreadCrumbModule], // no RouterTestingModule + declarations: [NzBreadcrumbAutoGenerateErrorDemoComponent] }); expect(() => { TestBed.compileComponents(); @@ -138,40 +148,37 @@ describe('breadcrumb', () => { ` }) -export class NzBreadcrumbAutoGenerateDemoComponent { -} +export class NzBreadcrumbAutoGenerateDemoComponent {} @Component({ selector: 'nz-breadcrumb-auto-generate-error-demo', template: '' }) -export class NzBreadcrumbAutoGenerateErrorDemoComponent { -} +export class NzBreadcrumbAutoGenerateErrorDemoComponent {} @Component({ selector: 'nz-breadcrumb-null', template: '' }) -export class NzBreadcrumbNullComponent { -} +export class NzBreadcrumbNullComponent {} const routes: Routes = [ { - path : 'one', + path: 'one', component: NzBreadcrumbAutoGenerateDemoComponent, - children : [ + children: [ { - path : 'two', + path: 'two', component: NzBreadcrumbNullComponent, - data : { breadcrumb: 'Layer 2' }, - children : [ + data: { breadcrumb: 'Layer 2' }, + children: [ { - path : 'three', + path: 'three', component: NzBreadcrumbNullComponent, - data : { breadcrumb: '' }, - children : [ + data: { breadcrumb: '' }, + children: [ { - path : 'four', + path: 'four', component: NzBreadcrumbNullComponent } ] @@ -179,8 +186,8 @@ const routes: Routes = [ ] }, { - path : 'two', - outlet : 'notprimary', + path: 'two', + outlet: 'notprimary', component: NzBreadcrumbNullComponent } ] diff --git a/components/button/demo/basic.ts b/components/button/demo/basic.ts index af98793e558..71347a31618 100644 --- a/components/button/demo/basic.ts +++ b/components/button/demo/basic.ts @@ -6,9 +6,10 @@ import { Component } from '@angular/core'; - `, - styles : [ - ` + + `, + styles: [ + ` [nz-button] { margin-right: 8px; margin-bottom: 12px; @@ -16,5 +17,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonBasicComponent { -} +export class NzDemoButtonBasicComponent {} diff --git a/components/button/demo/block.ts b/components/button/demo/block.ts index 523bcc202e4..edc33da7993 100644 --- a/components/button/demo/block.ts +++ b/components/button/demo/block.ts @@ -6,14 +6,14 @@ import { Component } from '@angular/core'; - `, - styles : [ - ` + + `, + styles: [ + ` [nz-button] { margin-bottom: 12px; } ` ] }) -export class NzDemoButtonBlockComponent { -} +export class NzDemoButtonBlockComponent {} diff --git a/components/button/demo/button-group.ts b/components/button/demo/button-group.ts index db3cb5c94dc..b63718a7ca4 100644 --- a/components/button/demo/button-group.ts +++ b/components/button/demo/button-group.ts @@ -27,9 +27,10 @@ import { Component } from '@angular/core'; - `, - styles : [ - ` + + `, + styles: [ + ` h4 { margin: 16px 0; font-size: 14px; @@ -52,5 +53,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonButtonGroupComponent { -} +export class NzDemoButtonButtonGroupComponent {} diff --git a/components/button/demo/disabled.ts b/components/button/demo/disabled.ts index a8ae7cbe012..35751830d5a 100644 --- a/components/button/demo/disabled.ts +++ b/components/button/demo/disabled.ts @@ -5,18 +5,19 @@ import { Component } from '@angular/core'; template: ` -
+
-
+
-
`, - styles : [ - ` + + `, + styles: [ + ` [nz-button] { margin-right: 8px; margin-bottom: 12px; @@ -24,5 +25,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonDisabledComponent { -} +export class NzDemoButtonDisabledComponent {} diff --git a/components/button/demo/ghost.ts b/components/button/demo/ghost.ts index e2556bcc8e1..cccaa5120f8 100644 --- a/components/button/demo/ghost.ts +++ b/components/button/demo/ghost.ts @@ -10,8 +10,8 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` [nz-button] { margin-right: 8px; margin-bottom: 12px; @@ -19,5 +19,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonGhostComponent { -} +export class NzDemoButtonGhostComponent {} diff --git a/components/button/demo/icon.ts b/components/button/demo/icon.ts index ccb4214325b..a3a6b59d887 100644 --- a/components/button/demo/icon.ts +++ b/components/button/demo/icon.ts @@ -7,13 +7,13 @@ import { Component } from '@angular/core'; -
+
`, - styles : [ + styles: [ ` [nz-button] { margin-right: 8px; @@ -22,5 +22,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonIconComponent { -} +export class NzDemoButtonIconComponent {} diff --git a/components/button/demo/loading.ts b/components/button/demo/loading.ts index bf7f93e89f9..2b035edb240 100644 --- a/components/button/demo/loading.ts +++ b/components/button/demo/loading.ts @@ -5,14 +5,16 @@ import { Component } from '@angular/core'; template: ` -
+
- -
+ +
`, - styles : [ + styles: [ ` [nz-button] { margin-right: 8px; diff --git a/components/button/demo/multiple.ts b/components/button/demo/multiple.ts index 4dcc84d6e32..75f6eb73a56 100644 --- a/components/button/demo/multiple.ts +++ b/components/button/demo/multiple.ts @@ -20,7 +20,7 @@ import { Component } from '@angular/core'; `, - styles : [ + styles: [ ` [nz-button] { margin-right: 8px; @@ -29,5 +29,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoButtonMultipleComponent { -} +export class NzDemoButtonMultipleComponent {} diff --git a/components/button/demo/size.ts b/components/button/demo/size.ts index b5815c292d8..6fc47ee6867 100644 --- a/components/button/demo/size.ts +++ b/components/button/demo/size.ts @@ -8,24 +8,24 @@ import { Component } from '@angular/core'; -
-
+
+
-
+
-
+
`, - styles : [ - ` + styles: [ + ` [nz-button] { margin-right: 8px; margin-bottom: 12px; diff --git a/components/button/nz-button-group.component.ts b/components/button/nz-button-group.component.ts index cf3cbf780a5..81a97691639 100644 --- a/components/button/nz-button-group.component.ts +++ b/components/button/nz-button-group.component.ts @@ -3,15 +3,14 @@ import { NzUpdateHostClassService } from '../core/services/update-host-class.ser import { NzSizeLDSType } from '../core/types/size'; @Component({ - selector : 'nz-button-group', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: 'nz-button-group', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - providers : [ NzUpdateHostClassService ], - templateUrl : './nz-button-group.component.html' + providers: [NzUpdateHostClassService], + templateUrl: './nz-button-group.component.html' }) export class NzButtonGroupComponent implements OnInit { - @Input() get nzSize(): NzSizeLDSType { return this._size; @@ -22,17 +21,16 @@ export class NzButtonGroupComponent implements OnInit { this.setClassMap(); } - constructor(private nzUpdateHostClassService: NzUpdateHostClassService, private elementRef: ElementRef) { - } + constructor(private nzUpdateHostClassService: NzUpdateHostClassService, private elementRef: ElementRef) {} private _size: NzSizeLDSType; private prefixCls = 'ant-btn-group'; setClassMap(): void { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-lg` ]: this.nzSize === 'large', - [ `${this.prefixCls}-sm` ]: this.nzSize === 'small' + [this.prefixCls]: true, + [`${this.prefixCls}-lg`]: this.nzSize === 'large', + [`${this.prefixCls}-sm`]: this.nzSize === 'small' }; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, classMap); } diff --git a/components/button/nz-button.component.ts b/components/button/nz-button.component.ts index c5dd44ef825..206775a4764 100644 --- a/components/button/nz-button.component.ts +++ b/components/button/nz-button.component.ts @@ -30,15 +30,15 @@ import { NzWaveConfig, NzWaveDirective, NZ_WAVE_GLOBAL_CONFIG } from '../core/wa import { NzIconDirective } from '../icon/nz-icon.directive'; export type NzButtonType = 'primary' | 'dashed' | 'danger' | 'default'; -export type NzButtonShape = 'circle' | 'round' | null ; +export type NzButtonShape = 'circle' | 'round' | null; @Component({ - selector : '[nz-button]', - providers : [ NzUpdateHostClassService ], + selector: '[nz-button]', + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-button.component.html' + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-button.component.html' }) export class NzButtonComponent implements AfterContentInit, OnInit, OnDestroy, OnChanges { readonly el: HTMLElement = this.elementRef.nativeElement; @@ -46,7 +46,12 @@ export class NzButtonComponent implements AfterContentInit, OnInit, OnDestroy, O private iconOnly = false; @ViewChild('contentElement') contentElement: ElementRef; @ContentChildren(NzIconDirective, { read: ElementRef }) listOfIconElement: QueryList; - @HostBinding('attr.nz-wave') nzWave = new NzWaveDirective(this.ngZone, this.elementRef, this.waveConfig, this.animationType); + @HostBinding('attr.nz-wave') nzWave = new NzWaveDirective( + this.ngZone, + this.elementRef, + this.waveConfig, + this.animationType + ); @Input() @InputBoolean() nzBlock = false; @Input() @InputBoolean() nzGhost = false; @Input() @InputBoolean() nzSearch = false; @@ -60,15 +65,15 @@ export class NzButtonComponent implements AfterContentInit, OnInit, OnDestroy, O const prefixCls = 'ant-btn'; const sizeMap: NzSizeMap = { large: 'lg', small: 'sm' }; this.nzUpdateHostClassService.updateHostClass(this.el, { - [ `${prefixCls}` ] : true, - [ `${prefixCls}-${this.nzType}` ] : this.nzType, - [ `${prefixCls}-${this.nzShape}` ] : this.nzShape, - [ `${prefixCls}-${sizeMap[ this.nzSize ]}` ]: sizeMap[ this.nzSize ], - [ `${prefixCls}-loading` ] : this.nzLoading, - [ `${prefixCls}-icon-only` ] : this.iconOnly, - [ `${prefixCls}-background-ghost` ] : this.nzGhost, - [ `${prefixCls}-block` ] : this.nzBlock, - [ `ant-input-search-button` ] : this.nzSearch + [`${prefixCls}`]: true, + [`${prefixCls}-${this.nzType}`]: this.nzType, + [`${prefixCls}-${this.nzShape}`]: this.nzShape, + [`${prefixCls}-${sizeMap[this.nzSize]}`]: sizeMap[this.nzSize], + [`${prefixCls}-loading`]: this.nzLoading, + [`${prefixCls}-icon-only`]: this.iconOnly, + [`${prefixCls}-background-ghost`]: this.nzGhost, + [`${prefixCls}-block`]: this.nzBlock, + [`ant-input-search-button`]: this.nzSearch }); } @@ -101,23 +106,24 @@ export class NzButtonComponent implements AfterContentInit, OnInit, OnDestroy, O if (this.listOfIconElement && this.listOfIconElement.length) { const firstChildElement = findFirstNotEmptyNode(this.contentElement.nativeElement); const lastChildElement = findLastNotEmptyNode(this.contentElement.nativeElement); - if (firstChildElement && (firstChildElement === this.listOfIconElement.first.nativeElement)) { + if (firstChildElement && firstChildElement === this.listOfIconElement.first.nativeElement) { this.renderer.insertBefore(this.el, firstChildElement, this.contentElement.nativeElement); this.iconElement = firstChildElement as HTMLElement; - } else if (lastChildElement && (lastChildElement === this.listOfIconElement.last.nativeElement)) { + } else if (lastChildElement && lastChildElement === this.listOfIconElement.last.nativeElement) { this.renderer.appendChild(this.el, lastChildElement); } } } - constructor(private elementRef: ElementRef, - private cdr: ChangeDetectorRef, - private renderer: Renderer2, - private nzUpdateHostClassService: NzUpdateHostClassService, - private ngZone: NgZone, - @Optional() @Inject(NZ_WAVE_GLOBAL_CONFIG) private waveConfig: NzWaveConfig, - @Optional() @Inject(ANIMATION_MODULE_TYPE) private animationType: string) { - } + constructor( + private elementRef: ElementRef, + private cdr: ChangeDetectorRef, + private renderer: Renderer2, + private nzUpdateHostClassService: NzUpdateHostClassService, + private ngZone: NgZone, + @Optional() @Inject(NZ_WAVE_GLOBAL_CONFIG) private waveConfig: NzWaveConfig, + @Optional() @Inject(ANIMATION_MODULE_TYPE) private animationType: string + ) {} ngAfterContentInit(): void { this.checkContent(); @@ -133,7 +139,15 @@ export class NzButtonComponent implements AfterContentInit, OnInit, OnDestroy, O } ngOnChanges(changes: SimpleChanges): void { - if (changes.nzBlock || changes.nzGhost || changes.nzSearch || changes.nzType || changes.nzShape || changes.nzSize || changes.nzLoading) { + if ( + changes.nzBlock || + changes.nzGhost || + changes.nzSearch || + changes.nzType || + changes.nzShape || + changes.nzSize || + changes.nzLoading + ) { this.setClassMap(); } if (changes.nzLoading) { diff --git a/components/button/nz-button.module.ts b/components/button/nz-button.module.ts index ca45a894608..fb1c664831b 100644 --- a/components/button/nz-button.module.ts +++ b/components/button/nz-button.module.ts @@ -8,9 +8,8 @@ import { NzButtonGroupComponent } from './nz-button-group.component'; import { NzButtonComponent } from './nz-button.component'; @NgModule({ - declarations : [ NzButtonComponent, NzButtonGroupComponent ], - exports : [ NzButtonComponent, NzButtonGroupComponent ], - imports : [ CommonModule, ObserversModule, NzWaveModule, NzIconModule ] + declarations: [NzButtonComponent, NzButtonGroupComponent], + exports: [NzButtonComponent, NzButtonGroupComponent], + imports: [CommonModule, ObserversModule, NzWaveModule, NzIconModule] }) -export class NzButtonModule { -} +export class NzButtonModule {} diff --git a/components/button/nz-button.spec.ts b/components/button/nz-button.spec.ts index 6a732dc1af2..2054a31b5f0 100644 --- a/components/button/nz-button.spec.ts +++ b/components/button/nz-button.spec.ts @@ -23,9 +23,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonBasicComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonBasicComponent], + providers: [] }).compileComponents(); })); @@ -36,10 +36,10 @@ describe('button', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-primary')).toBe(true); - expect(buttons[ 1 ].nativeElement.classList.contains('ant-btn-default')).toBe(true); - expect(buttons[ 2 ].nativeElement.classList.contains('ant-btn-dashed')).toBe(true); - expect(buttons[ 3 ].nativeElement.classList.contains('ant-btn-danger')).toBe(true); + expect(buttons[0].nativeElement.classList.contains('ant-btn-primary')).toBe(true); + expect(buttons[1].nativeElement.classList.contains('ant-btn-default')).toBe(true); + expect(buttons[2].nativeElement.classList.contains('ant-btn-dashed')).toBe(true); + expect(buttons[3].nativeElement.classList.contains('ant-btn-danger')).toBe(true); }); }); @@ -49,9 +49,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonButtonGroupComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonButtonGroupComponent], + providers: [] }).compileComponents(); })); @@ -66,8 +66,10 @@ describe('button', () => { }); it('should have no white space', () => { fixture.detectChanges(); - // @ts-ignore - expect(Array.from(buttonGroup.nativeElement.firstElementChild).some((node: HTMLElement) => node.nodeType === 3)).toBe(false); + expect( + // @ts-ignore + Array.from(buttonGroup.nativeElement.firstElementChild).some((node: HTMLElement) => node.nodeType === 3) + ).toBe(false); }); }); @@ -77,9 +79,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonDisabledComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonDisabledComponent], + providers: [] }).compileComponents(); })); @@ -90,7 +92,7 @@ describe('button', () => { it('should have correct attribute', () => { fixture.detectChanges(); - expect(!!buttons[ 1 ].nativeElement.attributes.getNamedItem('disabled')).toBe(true); + expect(!!buttons[1].nativeElement.attributes.getNamedItem('disabled')).toBe(true); }); }); @@ -100,9 +102,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonGhostComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonGhostComponent], + providers: [] }).compileComponents(); })); @@ -113,10 +115,10 @@ describe('button', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); - expect(buttons[ 1 ].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); - expect(buttons[ 2 ].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); - expect(buttons[ 3 ].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); + expect(buttons[0].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); + expect(buttons[1].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); + expect(buttons[2].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); + expect(buttons[3].nativeElement.classList.contains('ant-btn-background-ghost')).toBe(true); }); }); @@ -126,9 +128,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule, NzIconTestModule ], - declarations: [ NzDemoButtonIconComponent ], - providers : [] + imports: [NzButtonModule, NzIconTestModule], + declarations: [NzDemoButtonIconComponent], + providers: [] }).compileComponents(); })); @@ -139,11 +141,11 @@ describe('button', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-icon-only')).toBe(true); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-circle')).toBe(true); - expect(buttons[ 1 ].nativeElement.classList.contains('ant-btn-icon-only')).toBe(false); - expect(buttons[ 1 ].nativeElement.firstElementChild!.classList.contains('anticon-search')).toBe(true); - expect(buttons[ 1 ].nativeElement.firstElementChild.style.cssText).toBe('display: inline-block;'); + expect(buttons[0].nativeElement.classList.contains('ant-btn-icon-only')).toBe(true); + expect(buttons[0].nativeElement.classList.contains('ant-btn-circle')).toBe(true); + expect(buttons[1].nativeElement.classList.contains('ant-btn-icon-only')).toBe(false); + expect(buttons[1].nativeElement.firstElementChild!.classList.contains('anticon-search')).toBe(true); + expect(buttons[1].nativeElement.firstElementChild.style.cssText).toBe('display: inline-block;'); }); }); @@ -153,9 +155,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule, NzIconTestModule ], - declarations: [ NzDemoButtonLoadingComponent ], - providers : [] + imports: [NzButtonModule, NzIconTestModule], + declarations: [NzDemoButtonLoadingComponent], + providers: [] }).compileComponents(); })); @@ -166,11 +168,11 @@ describe('button', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-loading')).toBe(true); + expect(buttons[0].nativeElement.classList.contains('ant-btn-loading')).toBe(true); }); it('should loading when click without icon', fakeAsync(() => { - const button = buttons[ 2 ]; + const button = buttons[2]; fixture.detectChanges(); expect(button.nativeElement.classList.contains('ant-btn-loading')).toBe(false); expect(button.nativeElement.firstElementChild.localName).toBe('span'); @@ -189,7 +191,7 @@ describe('button', () => { })); it('should loading when click with icon', fakeAsync(() => { - const button = buttons[ 3 ]; + const button = buttons[3]; fixture.detectChanges(); expect(button.nativeElement.classList.contains('ant-btn-loading')).toBe(false); expect(button.nativeElement.firstElementChild.querySelector('svg')).not.toBe(null); @@ -222,10 +224,10 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonSizeComponent ], - schemas : [ NO_ERRORS_SCHEMA ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonSizeComponent], + schemas: [NO_ERRORS_SCHEMA], + providers: [] }).compileComponents(); })); @@ -257,9 +259,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzTestButtonSearchComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzTestButtonSearchComponent], + providers: [] }).compileComponents(); })); @@ -280,9 +282,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule ], - declarations: [ NzDemoButtonBlockComponent ], - providers : [] + imports: [NzButtonModule], + declarations: [NzDemoButtonBlockComponent], + providers: [] }).compileComponents(); })); @@ -293,15 +295,15 @@ describe('button', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-primary')).toBe(true); - expect(buttons[ 1 ].nativeElement.classList.contains('ant-btn-default')).toBe(true); - expect(buttons[ 2 ].nativeElement.classList.contains('ant-btn-dashed')).toBe(true); - expect(buttons[ 3 ].nativeElement.classList.contains('ant-btn-danger')).toBe(true); - - expect(buttons[ 0 ].nativeElement.classList.contains('ant-btn-block')).toBe(true); - expect(buttons[ 1 ].nativeElement.classList.contains('ant-btn-block')).toBe(true); - expect(buttons[ 2 ].nativeElement.classList.contains('ant-btn-block')).toBe(true); - expect(buttons[ 3 ].nativeElement.classList.contains('ant-btn-block')).toBe(true); + expect(buttons[0].nativeElement.classList.contains('ant-btn-primary')).toBe(true); + expect(buttons[1].nativeElement.classList.contains('ant-btn-default')).toBe(true); + expect(buttons[2].nativeElement.classList.contains('ant-btn-dashed')).toBe(true); + expect(buttons[3].nativeElement.classList.contains('ant-btn-danger')).toBe(true); + + expect(buttons[0].nativeElement.classList.contains('ant-btn-block')).toBe(true); + expect(buttons[1].nativeElement.classList.contains('ant-btn-block')).toBe(true); + expect(buttons[2].nativeElement.classList.contains('ant-btn-block')).toBe(true); + expect(buttons[3].nativeElement.classList.contains('ant-btn-block')).toBe(true); }); }); @@ -311,9 +313,9 @@ describe('button', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzButtonModule, NzIconTestModule ], - declarations: [ NzTestButtonBindingComponent ], - providers : [] + imports: [NzButtonModule, NzIconTestModule], + declarations: [NzTestButtonBindingComponent], + providers: [] }).compileComponents(); })); @@ -349,21 +351,25 @@ describe('button', () => { @Component({ selector: 'nz-test-button-search', template: ` - ` + + ` }) -export class NzTestButtonSearchComponent { -} +export class NzTestButtonSearchComponent {} // https://github.com/NG-ZORRO/ng-zorro-antd/issues/2191 @Component({ selector: 'nz-test-button-binding', - template: `` + template: ` + + ` }) export class NzTestButtonBindingComponent { loading = false; load(): void { this.loading = true; - setTimeout(() => this.loading = false, 5000); + setTimeout(() => (this.loading = false), 5000); } } diff --git a/components/calendar/demo/basic.ts b/components/calendar/demo/basic.ts index d86333b5e6e..7eb01ab8684 100644 --- a/components/calendar/demo/basic.ts +++ b/components/calendar/demo/basic.ts @@ -10,8 +10,7 @@ export class NzDemoCalendarBasicComponent { date = new Date(2012, 11, 21); mode = 'month'; - panelChange(change: {date: Date, mode: string}): void { + panelChange(change: { date: Date; mode: string }): void { console.log(change.date, change.mode); } - } diff --git a/components/calendar/demo/card.ts b/components/calendar/demo/card.ts index f2da77be67f..28b617e8f6c 100644 --- a/components/calendar/demo/card.ts +++ b/components/calendar/demo/card.ts @@ -4,7 +4,11 @@ import { Component } from '@angular/core'; selector: 'nz-demo-calendar-card', template: `
- +
` }) @@ -13,7 +17,7 @@ export class NzDemoCalendarCardComponent { console.log(`Current value: ${value}`); } - onPanelChange(change: {date: Date, mode: string}): void { + onPanelChange(change: { date: Date; mode: string }): void { console.log(`Current value: ${change.date}`); console.log(`Current mode: ${change.mode}`); } diff --git a/components/calendar/demo/notice-calendar.ts b/components/calendar/demo/notice-calendar.ts index 3c8fc35178d..17fd9eff59c 100644 --- a/components/calendar/demo/notice-calendar.ts +++ b/components/calendar/demo/notice-calendar.ts @@ -31,38 +31,40 @@ import { Component } from '@angular/core'; `, - styles : [ ` - .events { - list-style: none; - margin: 0; - padding: 0; - } + styles: [ + ` + .events { + list-style: none; + margin: 0; + padding: 0; + } - .events .ant-badge-status { - overflow: hidden; - white-space: nowrap; - width: 100%; - text-overflow: ellipsis; - font-size: 12px; - } + .events .ant-badge-status { + overflow: hidden; + white-space: nowrap; + width: 100%; + text-overflow: ellipsis; + font-size: 12px; + } - .notes-month { - text-align: center; - font-size: 28px; - } + .notes-month { + text-align: center; + font-size: 28px; + } - .notes-month section { - font-size: 28px; - } - ` ] + .notes-month section { + font-size: 28px; + } + ` + ] }) export class NzDemoCalendarNoticeCalendarComponent { listDataMap = { - eight : [ + eight: [ { type: 'warning', content: 'This is warning event.' }, { type: 'success', content: 'This is usual event.' } ], - ten : [ + ten: [ { type: 'warning', content: 'This is warning event.' }, { type: 'success', content: 'This is usual event.' }, { type: 'error', content: 'This is error event.' } diff --git a/components/calendar/demo/select.ts b/components/calendar/demo/select.ts index 8283261fb40..fddf1df4a36 100644 --- a/components/calendar/demo/select.ts +++ b/components/calendar/demo/select.ts @@ -3,10 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-calendar-select', template: ` - - + + ` }) export class NzDemoCalendarSelectComponent { diff --git a/components/calendar/nz-calendar-cells.ts b/components/calendar/nz-calendar-cells.ts index f79b606b85c..572eb4ca8b8 100644 --- a/components/calendar/nz-calendar-cells.ts +++ b/components/calendar/nz-calendar-cells.ts @@ -3,19 +3,19 @@ import { Directive } from '@angular/core'; @Directive({ selector: '[nzDateCell]' }) -export class NzDateCellDirective { } +export class NzDateCellDirective {} @Directive({ selector: '[nzMonthCell]' }) -export class NzMonthCellDirective { } +export class NzMonthCellDirective {} @Directive({ selector: '[nzDateFullCell]' }) -export class NzDateFullCellDirective { } +export class NzDateFullCellDirective {} @Directive({ selector: '[nzMonthFullCell]' }) -export class NzMonthFullCellDirective { } +export class NzMonthFullCellDirective {} diff --git a/components/calendar/nz-calendar-header.component.ts b/components/calendar/nz-calendar-header.component.ts index 4158779f5c6..c023954d9e9 100644 --- a/components/calendar/nz-calendar-header.component.ts +++ b/components/calendar/nz-calendar-header.component.ts @@ -1,4 +1,12 @@ -import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + EventEmitter, + Input, + OnInit, + Output, + ViewEncapsulation +} from '@angular/core'; import setMonth from 'date-fns/set_month'; import { DateHelperService } from '../i18n/date-helper.service'; import { NzI18nService as I18n } from '../i18n/nz-i18n.service'; @@ -6,10 +14,10 @@ import { NzI18nService as I18n } from '../i18n/nz-i18n.service'; @Component({ encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-calendar-header', + selector: 'nz-calendar-header', templateUrl: './nz-calendar-header.component.html', - host : { - '[style.display]' : `'block'`, + host: { + '[style.display]': `'block'`, '[class.ant-fullcalendar-header]': `true` } }) @@ -35,8 +43,8 @@ export class NzCalendarHeaderComponent implements OnInit { _activeDate = new Date(); yearOffset: number = 10; yearTotal: number = 20; - years: Array<{ label: string, value: number }>; - months: Array<{ label: string, value: number }>; + years: Array<{ label: string; value: number }>; + months: Array<{ label: string; value: number }>; get activeYear(): number { return this.activeDate.getFullYear(); @@ -58,8 +66,7 @@ export class NzCalendarHeaderComponent implements OnInit { return this.i18n.getLocale().Calendar.month; } - constructor(private i18n: I18n, private dateHelper: DateHelperService) { - } + constructor(private i18n: I18n, private dateHelper: DateHelperService) {} ngOnInit(): void { this.setUpYears(); diff --git a/components/calendar/nz-calendar-header.spec.ts b/components/calendar/nz-calendar-header.spec.ts index 6fedad67220..85f5028ac34 100644 --- a/components/calendar/nz-calendar-header.spec.ts +++ b/components/calendar/nz-calendar-header.spec.ts @@ -16,13 +16,7 @@ registerLocaleData(zh); describe('Calendar Header', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports: [ - FormsModule, - NzI18nModule, - NzRadioModule, - NzSelectModule, - NoopAnimationsModule - ], + imports: [FormsModule, NzI18nModule, NzRadioModule, NzSelectModule, NoopAnimationsModule], declarations: [ CalendarHeader, NzTestCalendarHeaderModeComponent, @@ -45,8 +39,10 @@ describe('Calendar Header', () => { it('should be month by default', () => { fixture.detectChanges(); - const modeNgModel = fixture.debugElement.queryAll(By.directive(CalendarHeader))[0] - .query(By.directive(RadioGroup)).injector.get(NgModel); + const modeNgModel = fixture.debugElement + .queryAll(By.directive(CalendarHeader))[0] + .query(By.directive(RadioGroup)) + .injector.get(NgModel); expect(modeNgModel.model).toBe('month'); }); @@ -55,14 +51,18 @@ describe('Calendar Header', () => { fixture.detectChanges(); - const modeNgModel = fixture.debugElement.queryAll(By.directive(CalendarHeader))[1] - .query(By.directive(RadioGroup)).injector.get(NgModel); + const modeNgModel = fixture.debugElement + .queryAll(By.directive(CalendarHeader))[1] + .query(By.directive(RadioGroup)) + .injector.get(NgModel); expect(modeNgModel.model).toBe('year'); }); it('should emit change event for mode selection', () => { - const modeNgModel = fixture.debugElement.queryAll(By.directive(CalendarHeader))[1] - .query(By.directive(RadioGroup)).injector.get(NgModel); + const modeNgModel = fixture.debugElement + .queryAll(By.directive(CalendarHeader))[1] + .query(By.directive(RadioGroup)) + .injector.get(NgModel); modeNgModel.viewToModelUpdate('year'); fixture.detectChanges(); @@ -186,7 +186,7 @@ describe('Calendar Header', () => { ` }) class NzTestCalendarHeaderModeComponent { - mode: 'month'|'year' = 'month'; + mode: 'month' | 'year' = 'month'; } @Component({ @@ -211,13 +211,10 @@ class NzTestCalendarHeaderActiveDateComponent { @Component({ template: ` - - + ` }) class NzTestCalendarHeaderChangesComponent { - year: number|null = null; - month: number|null = null; + year: number | null = null; + month: number | null = null; } diff --git a/components/calendar/nz-calendar.component.ts b/components/calendar/nz-calendar.component.ts index 9edd52ea448..005644ccca8 100644 --- a/components/calendar/nz-calendar.component.ts +++ b/components/calendar/nz-calendar.component.ts @@ -1,5 +1,18 @@ import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { forwardRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, EventEmitter, HostBinding, Input, OnInit, Output, TemplateRef, ViewEncapsulation } from '@angular/core'; +import { + forwardRef, + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + ContentChild, + EventEmitter, + HostBinding, + Input, + OnInit, + Output, + TemplateRef, + ViewEncapsulation +} from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import addDays from 'date-fns/add_days'; import differenceInCalendarDays from 'date-fns/difference_in_calendar_days'; @@ -18,7 +31,12 @@ import startOfWeek from 'date-fns/start_of_week'; import startOfYear from 'date-fns/start_of_year'; import { DateHelperService } from '../i18n/date-helper.service'; import { NzI18nService } from '../i18n/nz-i18n.service'; -import { NzDateCellDirective as DateCell, NzDateFullCellDirective as DateFullCell, NzMonthCellDirective as MonthCell, NzMonthFullCellDirective as MonthFullCell } from './nz-calendar-cells'; +import { + NzDateCellDirective as DateCell, + NzDateFullCellDirective as DateFullCell, + NzMonthCellDirective as MonthCell, + NzMonthFullCellDirective as MonthFullCell +} from './nz-calendar-cells'; export type ModeType = 'month' | 'year'; @@ -27,51 +45,83 @@ export type ModeType = 'month' | 'year'; changeDetection: ChangeDetectionStrategy.OnPush, selector: 'nz-calendar', templateUrl: './nz-calendar.component.html', - providers: [ - { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzCalendarComponent), multi: true } - ] + providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzCalendarComponent), multi: true }] }) export class NzCalendarComponent implements ControlValueAccessor, OnInit { @Input() nzMode: ModeType = 'month'; @Output() readonly nzModeChange: EventEmitter = new EventEmitter(); - @Output() readonly nzPanelChange: EventEmitter<{date: Date, mode: ModeType}> = new EventEmitter(); + @Output() readonly nzPanelChange: EventEmitter<{ date: Date; mode: ModeType }> = new EventEmitter(); @Output() readonly nzSelectChange: EventEmitter = new EventEmitter(); - @Input() set nzValue(value: Date) { this.updateDate(value, false); } + @Input() set nzValue(value: Date) { + this.updateDate(value, false); + } @Output() readonly nzValueChange: EventEmitter = new EventEmitter(); @Input() - set nzDateCell(value: TemplateRef<{$implicit: Date}>) { this.dateCell = value; } + set nzDateCell(value: TemplateRef<{ $implicit: Date }>) { + this.dateCell = value; + } @Input() - set nzDateFullCell(value: TemplateRef<{$implicit: Date}>) { this.dateFullCell = value; } + set nzDateFullCell(value: TemplateRef<{ $implicit: Date }>) { + this.dateFullCell = value; + } @Input() - set nzMonthCell(value: TemplateRef<{$implicit: Date}>) { this.monthCell = value; } + set nzMonthCell(value: TemplateRef<{ $implicit: Date }>) { + this.monthCell = value; + } @Input() - set nzMonthFullCell(value: TemplateRef<{$implicit: Date}>) { this.monthFullCell = value; } + set nzMonthFullCell(value: TemplateRef<{ $implicit: Date }>) { + this.monthFullCell = value; + } @Input() - set nzFullscreen(value: boolean) { this.fullscreen = coerceBooleanProperty(value); } - get nzFullscreen(): boolean { return this.fullscreen; } + set nzFullscreen(value: boolean) { + this.fullscreen = coerceBooleanProperty(value); + } + get nzFullscreen(): boolean { + return this.fullscreen; + } @Input() - set nzCard(value: boolean) { this.fullscreen = !coerceBooleanProperty(value); } - get nzCard(): boolean { return !this.fullscreen; } + set nzCard(value: boolean) { + this.fullscreen = !coerceBooleanProperty(value); + } + get nzCard(): boolean { + return !this.fullscreen; + } - @ContentChild(DateCell, {read: TemplateRef}) - set dateCellChild(value: TemplateRef<{$implicit: Date}>) { if (value) { this.dateCell = value; } } + @ContentChild(DateCell, { read: TemplateRef }) + set dateCellChild(value: TemplateRef<{ $implicit: Date }>) { + if (value) { + this.dateCell = value; + } + } - @ContentChild(DateFullCell, {read: TemplateRef}) - set dateFullCellChild(value: TemplateRef<{$implicit: Date}>) { if (value) { this.dateFullCell = value; } } + @ContentChild(DateFullCell, { read: TemplateRef }) + set dateFullCellChild(value: TemplateRef<{ $implicit: Date }>) { + if (value) { + this.dateFullCell = value; + } + } - @ContentChild(MonthCell, {read: TemplateRef}) - set monthCellChild(value: TemplateRef<{$implicit: Date}>) { if (value) { this.monthCell = value; } } + @ContentChild(MonthCell, { read: TemplateRef }) + set monthCellChild(value: TemplateRef<{ $implicit: Date }>) { + if (value) { + this.monthCell = value; + } + } - @ContentChild(MonthFullCell, {read: TemplateRef}) - set monthFullCellChild(value: TemplateRef<{$implicit: Date}>) { if (value) { this.monthFullCell = value; } } + @ContentChild(MonthFullCell, { read: TemplateRef }) + set monthFullCellChild(value: TemplateRef<{ $implicit: Date }>) { + if (value) { + this.monthFullCell = value; + } + } @HostBinding('class.ant-fullcalendar--fullscreen') fullscreen = true; @@ -88,10 +138,10 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { currentMonthCol: number = -1; activeMonthRow: number = -1; activeMonthCol: number = -1; - dateCell: TemplateRef<{$implicit: Date}>|null = null; - dateFullCell: TemplateRef<{$implicit: Date}>|null = null; - monthCell: TemplateRef<{$implicit: Date}>|null = null; - monthFullCell: TemplateRef<{$implicit: Date}>|null = null; + dateCell: TemplateRef<{ $implicit: Date }> | null = null; + dateFullCell: TemplateRef<{ $implicit: Date }> | null = null; + monthCell: TemplateRef<{ $implicit: Date }> | null = null; + monthFullCell: TemplateRef<{ $implicit: Date }> | null = null; private currentDate = new Date(); private onChangeFn: (date: Date) => void = () => {}; @@ -101,7 +151,7 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { return startOfWeek(startOfMonth(this.activeDate), { weekStartsOn: this.dateHelper.getFirstDayOfWeek() }); } - constructor(private i18n: NzI18nService, private cdr: ChangeDetectorRef, private dateHelper: DateHelperService) { } + constructor(private i18n: NzI18nService, private cdr: ChangeDetectorRef, private dateHelper: DateHelperService) {} ngOnInit(): void { this.setUpDaysInWeek(); @@ -115,7 +165,7 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { onModeChange(mode: ModeType): void { this.nzModeChange.emit(mode); - this.nzPanelChange.emit({'date': this.activeDate, 'mode': mode}); + this.nzPanelChange.emit({ date: this.activeDate, mode }); } onDateSelect(date: Date): void { @@ -135,7 +185,7 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { this.nzSelectChange.emit(date); } - writeValue(value: Date|null): void { + writeValue(value: Date | null): void { this.updateDate(value || new Date(), false); this.cdr.markForCheck(); } @@ -181,7 +231,7 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { const date = addDays(weekStart, i); const title = this.dateHelper.format(date, this.dateHelper.relyOnDatePipe ? 'E' : 'ddd'); const label = this.dateHelper.format(date, this.dateHelper.relyOnDatePipe ? 'EEEEEE' : 'dd'); - this.daysInWeek.push({title, label}); + this.daysInWeek.push({ title, label }); } } @@ -192,7 +242,7 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { const title = this.dateHelper.format(date, 'MMM'); const label = this.dateHelper.format(date, 'MMM'); const start = startOfMonth(date); - this.monthsInYear.push({title, label, start}); + this.monthsInYear.push({ title, label, start }); } } @@ -200,7 +250,8 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { this.dateMatrix = []; const monthStart = startOfMonth(this.activeDate); const monthEnd = endOfMonth(this.activeDate); - const weekDiff = differenceInCalendarWeeks(monthEnd, monthStart, { weekStartsOn: this.dateHelper.getFirstDayOfWeek() }) + 2; + const weekDiff = + differenceInCalendarWeeks(monthEnd, monthStart, { weekStartsOn: this.dateHelper.getFirstDayOfWeek() }) + 2; for (let week = 0; week < weekDiff; week++) { const row: DateCellContext[] = []; @@ -209,11 +260,13 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { for (let day = 0; day < 7; day++) { const date = addDays(weekStart, day); const monthDiff = differenceInCalendarMonths(date, this.activeDate); - const dateFormat = this.dateHelper.relyOnDatePipe ? 'longDate' : this.i18n.getLocaleData('DatePicker.lang.dateFormat', 'YYYY-MM-DD'); + const dateFormat = this.dateHelper.relyOnDatePipe + ? 'longDate' + : this.i18n.getLocaleData('DatePicker.lang.dateFormat', 'YYYY-MM-DD'); const title = this.dateHelper.format(date, dateFormat); const label = this.dateHelper.format(date, this.dateHelper.relyOnDatePipe ? 'dd' : 'DD'); const rel = monthDiff === 0 ? 'current' : monthDiff < 0 ? 'last' : 'next'; - row.push({title, label, rel, value: date}); + row.push({ title, label, rel, value: date }); } this.dateMatrix.push(row); } @@ -221,8 +274,13 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { private calculateCurrentDate(): void { if (isThisMonth(this.activeDate)) { - this.currentDateRow = differenceInCalendarWeeks(this.currentDate, this.calendarStart, { weekStartsOn: this.dateHelper.getFirstDayOfWeek() }); - this.currentDateCol = differenceInCalendarDays(this.currentDate, addDays(this.calendarStart, this.currentDateRow * 7)); + this.currentDateRow = differenceInCalendarWeeks(this.currentDate, this.calendarStart, { + weekStartsOn: this.dateHelper.getFirstDayOfWeek() + }); + this.currentDateCol = differenceInCalendarDays( + this.currentDate, + addDays(this.calendarStart, this.currentDateRow * 7) + ); } else { this.currentDateRow = -1; this.currentDateCol = -1; @@ -230,7 +288,9 @@ export class NzCalendarComponent implements ControlValueAccessor, OnInit { } private calculateActiveDate(): void { - this.activeDateRow = differenceInCalendarWeeks(this.activeDate, this.calendarStart, { weekStartsOn: this.dateHelper.getFirstDayOfWeek() }); + this.activeDateRow = differenceInCalendarWeeks(this.activeDate, this.calendarStart, { + weekStartsOn: this.dateHelper.getFirstDayOfWeek() + }); this.activeDateCol = differenceInCalendarDays(this.activeDate, addDays(this.calendarStart, this.activeDateRow * 7)); } @@ -266,6 +326,6 @@ export interface MonthCellContext { export interface DateCellContext { title: string; label: string; - rel: 'last'|'current'|'next'; + rel: 'last' | 'current' | 'next'; value: Date; } diff --git a/components/calendar/nz-calendar.module.ts b/components/calendar/nz-calendar.module.ts index 42b683cc43e..08182017cd0 100644 --- a/components/calendar/nz-calendar.module.ts +++ b/components/calendar/nz-calendar.module.ts @@ -4,7 +4,12 @@ import { FormsModule } from '@angular/forms'; import { NzI18nModule } from '../i18n/nz-i18n.module'; import { NzRadioModule } from '../radio/nz-radio.module'; import { NzSelectModule } from '../select/nz-select.module'; -import { NzDateCellDirective, NzDateFullCellDirective, NzMonthCellDirective, NzMonthFullCellDirective } from './nz-calendar-cells'; +import { + NzDateCellDirective, + NzDateFullCellDirective, + NzMonthCellDirective, + NzMonthFullCellDirective +} from './nz-calendar-cells'; import { NzCalendarHeaderComponent } from './nz-calendar-header.component'; import { NzCalendarComponent } from './nz-calendar.component'; @@ -17,13 +22,13 @@ import { NzCalendarComponent } from './nz-calendar.component'; NzMonthCellDirective, NzMonthFullCellDirective ], - exports : [ + exports: [ NzCalendarComponent, NzDateCellDirective, NzDateFullCellDirective, NzMonthCellDirective, NzMonthFullCellDirective ], - imports : [ CommonModule, FormsModule, NzI18nModule, NzRadioModule, NzSelectModule ] + imports: [CommonModule, FormsModule, NzI18nModule, NzRadioModule, NzSelectModule] }) -export class NzCalendarModule { } +export class NzCalendarModule {} diff --git a/components/calendar/nz-calendar.spec.ts b/components/calendar/nz-calendar.spec.ts index 2b0093b215f..eb3d0a47dd4 100644 --- a/components/calendar/nz-calendar.spec.ts +++ b/components/calendar/nz-calendar.spec.ts @@ -1,7 +1,7 @@ import { registerLocaleData } from '@angular/common'; import zh from '@angular/common/locales/zh'; import { Component } from '@angular/core'; -import { async, fakeAsync, flush, ComponentFixture , TestBed } from '@angular/core/testing'; +import { async, fakeAsync, flush, ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, NgModel } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; @@ -15,11 +15,7 @@ registerLocaleData(zh); describe('Calendar', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports: [ - FormsModule, - NzCalendarModule, - NoopAnimationsModule - ], + imports: [FormsModule, NzCalendarModule, NoopAnimationsModule], declarations: [ NzTestCalendarModeComponent, NzTestCalendarValueComponent, @@ -30,7 +26,7 @@ describe('Calendar', () => { NzTestCalendarMonthFullCellComponent, NzTestCalendarChangesComponent ], - providers: [ { provide: NZ_DATE_CONFIG, useValue: { firstDayOfWeek: 0 } } ] + providers: [{ provide: NZ_DATE_CONFIG, useValue: { firstDayOfWeek: 0 } }] }).compileComponents(); })); @@ -46,8 +42,10 @@ describe('Calendar', () => { it('should be month by default', () => { fixture.detectChanges(); - const header = fixture.debugElement.queryAll(By.directive(Calendar))[0] - .query(By.directive(CalendarHeader)).injector.get(CalendarHeader); + const header = fixture.debugElement + .queryAll(By.directive(Calendar))[0] + .query(By.directive(CalendarHeader)) + .injector.get(CalendarHeader); expect(header.mode).toBe('month'); }); @@ -56,14 +54,18 @@ describe('Calendar', () => { fixture.detectChanges(); - const header = fixture.debugElement.queryAll(By.directive(Calendar))[1] - .query(By.directive(CalendarHeader)).injector.get(CalendarHeader); + const header = fixture.debugElement + .queryAll(By.directive(Calendar))[1] + .query(By.directive(CalendarHeader)) + .injector.get(CalendarHeader); expect(header.mode).toBe('year'); }); it('should emit change event for mode selection', () => { - const header = fixture.debugElement.queryAll(By.directive(Calendar))[1] - .query(By.directive(CalendarHeader)).injector.get(CalendarHeader); + const header = fixture.debugElement + .queryAll(By.directive(Calendar))[1] + .query(By.directive(CalendarHeader)) + .injector.get(CalendarHeader); header.modeChange.emit('year'); fixture.detectChanges(); @@ -418,7 +420,6 @@ describe('Calendar', () => { expect(component.selectChange).toHaveBeenCalledTimes(2); }); }); - }); @Component({ @@ -428,7 +429,7 @@ describe('Calendar', () => { ` }) class NzTestCalendarModeComponent { - mode: 'month'|'year' = 'month'; + mode: 'month' | 'year' = 'month'; } @Component({ @@ -467,7 +468,7 @@ class NzTestCalendarFullscreenComponent { ` }) -class NzTestCalendarDateCellComponent { } +class NzTestCalendarDateCellComponent {} @Component({ template: ` @@ -478,7 +479,7 @@ class NzTestCalendarDateCellComponent { } ` }) -class NzTestCalendarDateFullCellComponent { } +class NzTestCalendarDateFullCellComponent {} @Component({ template: ` @@ -489,7 +490,7 @@ class NzTestCalendarDateFullCellComponent { } ` }) -class NzTestCalendarMonthCellComponent { } +class NzTestCalendarMonthCellComponent {} @Component({ template: ` @@ -500,7 +501,7 @@ class NzTestCalendarMonthCellComponent { } ` }) -class NzTestCalendarMonthFullCellComponent { } +class NzTestCalendarMonthFullCellComponent {} @Component({ template: ` @@ -508,12 +509,13 @@ class NzTestCalendarMonthFullCellComponent { } [(nzMode)]="mode" [(ngModel)]="date0" (nzPanelChange)="panelChange($event)" - (nzSelectChange)="selectChange($event)"> + (nzSelectChange)="selectChange($event)" + > ` }) class NzTestCalendarChangesComponent { - mode: 'month'|'year' = 'month'; + mode: 'month' | 'year' = 'month'; date0 = new Date(2014, 3, 14); panelChange = jasmine.createSpy('panelChange callback'); selectChange = jasmine.createSpy('selectChange callback'); diff --git a/components/card/demo/basic.ts b/components/card/demo/basic.ts index 2e2283b82da..083234f3b12 100644 --- a/components/card/demo/basic.ts +++ b/components/card/demo/basic.ts @@ -12,11 +12,12 @@ import { Component } from '@angular/core'; More `, - styles : [ - `p { - margin: 0; - }` + styles: [ + ` + p { + margin: 0; + } + ` ] }) -export class NzDemoCardBasicComponent { -} +export class NzDemoCardBasicComponent {} diff --git a/components/card/demo/border-less.ts b/components/card/demo/border-less.ts index 10c66918656..400c07ae8b8 100644 --- a/components/card/demo/border-less.ts +++ b/components/card/demo/border-less.ts @@ -14,11 +14,12 @@ import { Component } from '@angular/core'; More `, - styles : [ - `p { - margin: 0; - }` + styles: [ + ` + p { + margin: 0; + } + ` ] }) -export class NzDemoCardBorderLessComponent { -} +export class NzDemoCardBorderLessComponent {} diff --git a/components/card/demo/flexible-content.ts b/components/card/demo/flexible-content.ts index 7983f8331f1..9063270248b 100644 --- a/components/card/demo/flexible-content.ts +++ b/components/card/demo/flexible-content.ts @@ -7,9 +7,8 @@ import { Component } from '@angular/core'; - example + example ` }) -export class NzDemoCardFlexibleContentComponent { -} +export class NzDemoCardFlexibleContentComponent {} diff --git a/components/card/demo/grid-card.ts b/components/card/demo/grid-card.ts index 70e511e6bb5..2f83c69f6d4 100644 --- a/components/card/demo/grid-card.ts +++ b/components/card/demo/grid-card.ts @@ -16,7 +16,7 @@ import { Component } from '@angular/core'; }) export class NzDemoCardGridCardComponent { gridStyle = { - width : '25%', + width: '25%', textAlign: 'center' }; } diff --git a/components/card/demo/in-column.ts b/components/card/demo/in-column.ts index 65e8d947f93..776f8e17aa8 100644 --- a/components/card/demo/in-column.ts +++ b/components/card/demo/in-column.ts @@ -23,11 +23,12 @@ import { Component } from '@angular/core'; `, - styles : [ - `p { - margin: 0; - }` + styles: [ + ` + p { + margin: 0; + } + ` ] }) -export class NzDemoCardInColumnComponent { -} +export class NzDemoCardInColumnComponent {} diff --git a/components/card/demo/inner.ts b/components/card/demo/inner.ts index 4d9eb9ec9a9..e04d42fc03d 100644 --- a/components/card/demo/inner.ts +++ b/components/card/demo/inner.ts @@ -19,5 +19,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoCardInnerComponent { -} +export class NzDemoCardInnerComponent {} diff --git a/components/card/demo/loading.ts b/components/card/demo/loading.ts index e7be0c3d510..612d00e7c97 100644 --- a/components/card/demo/loading.ts +++ b/components/card/demo/loading.ts @@ -4,16 +4,20 @@ import { Component } from '@angular/core'; selector: 'nz-demo-card-loading', template: ` - - + + - - - + + + diff --git a/components/card/demo/meta.ts b/components/card/demo/meta.ts index 6d7c8257029..3c02de62a72 100644 --- a/components/card/demo/meta.ts +++ b/components/card/demo/meta.ts @@ -3,14 +3,18 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-card-meta', template: ` - - + + - example + example @@ -23,5 +27,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoCardMetaComponent { -} +export class NzDemoCardMetaComponent {} diff --git a/components/card/demo/simple.ts b/components/card/demo/simple.ts index e36f1fea181..31232566504 100644 --- a/components/card/demo/simple.ts +++ b/components/card/demo/simple.ts @@ -9,11 +9,12 @@ import { Component } from '@angular/core';

Card content

`, - styles : [ - `p { - margin: 0; - }` + styles: [ + ` + p { + margin: 0; + } + ` ] }) -export class NzDemoCardSimpleComponent { -} +export class NzDemoCardSimpleComponent {} diff --git a/components/card/demo/tabs.ts b/components/card/demo/tabs.ts index 5773f03d976..5ed9d3167b6 100644 --- a/components/card/demo/tabs.ts +++ b/components/card/demo/tabs.ts @@ -15,8 +15,8 @@ import { Component } from '@angular/core'; More -
-
+
+
diff --git a/components/card/nz-card-loading.component.ts b/components/card/nz-card-loading.component.ts index a24ad4ecbf2..a3599547c7d 100644 --- a/components/card/nz-card-loading.component.ts +++ b/components/card/nz-card-loading.component.ts @@ -1,16 +1,18 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-card-loading', - templateUrl : './nz-card-loading.component.html', + selector: 'nz-card-loading', + templateUrl: './nz-card-loading.component.html', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - styles : [ ` - nz-card-loading { - display: block; - } - ` ] + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + styles: [ + ` + nz-card-loading { + display: block; + } + ` + ] }) export class NzCardLoadingComponent { constructor(elementRef: ElementRef, renderer: Renderer2) { diff --git a/components/card/nz-card-meta.component.ts b/components/card/nz-card-meta.component.ts index d2cb22164b8..d0ac573d7da 100755 --- a/components/card/nz-card-meta.component.ts +++ b/components/card/nz-card-meta.component.ts @@ -9,16 +9,18 @@ import { } from '@angular/core'; @Component({ - selector : 'nz-card-meta', + selector: 'nz-card-meta', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-card-meta.component.html', - styles : [ ` - nz-card-meta { - display: block; - } - ` ] + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-card-meta.component.html', + styles: [ + ` + nz-card-meta { + display: block; + } + ` + ] }) export class NzCardMetaComponent { @Input() nzTitle: string | TemplateRef; diff --git a/components/card/nz-card-tab.component.ts b/components/card/nz-card-tab.component.ts index 65ab14a8da7..fa9977ba1db 100644 --- a/components/card/nz-card-tab.component.ts +++ b/components/card/nz-card-tab.component.ts @@ -1,10 +1,10 @@ import { ChangeDetectionStrategy, Component, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-card-tab', - encapsulation : ViewEncapsulation.None, + selector: 'nz-card-tab', + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl : './nz-card-tab.component.html' + templateUrl: './nz-card-tab.component.html' }) export class NzCardTabComponent { @ViewChild(TemplateRef) template: TemplateRef; diff --git a/components/card/nz-card.component.ts b/components/card/nz-card.component.ts index 58e8d6ef8ed..8e215606acd 100755 --- a/components/card/nz-card.component.ts +++ b/components/card/nz-card.component.ts @@ -1,8 +1,10 @@ import { ChangeDetectionStrategy, Component, - ContentChild, ElementRef, - Input, Renderer2, + ContentChild, + ElementRef, + Input, + Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -10,21 +12,23 @@ import { InputBoolean } from '../core/util/convert'; import { NzCardTabComponent } from './nz-card-tab.component'; @Component({ - selector : 'nz-card', + selector: 'nz-card', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-card.component.html', - styles : [ ` - nz-card { - display: block; - } - ` ], - host : { - '[class.ant-card-loading]' : 'nzLoading', - '[class.ant-card-bordered]' : 'nzBordered', - '[class.ant-card-hoverable]' : 'nzHoverable', - '[class.ant-card-type-inner]' : `nzType === 'inner'`, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-card.component.html', + styles: [ + ` + nz-card { + display: block; + } + ` + ], + host: { + '[class.ant-card-loading]': 'nzLoading', + '[class.ant-card-bordered]': 'nzBordered', + '[class.ant-card-hoverable]': 'nzHoverable', + '[class.ant-card-type-inner]': `nzType === 'inner'`, '[class.ant-card-contain-tabs]': '!!tab' } }) @@ -32,7 +36,7 @@ export class NzCardComponent { @Input() @InputBoolean() nzBordered = true; @Input() @InputBoolean() nzLoading = false; @Input() @InputBoolean() nzHoverable = false; - @Input() nzBodyStyle: { [ key: string ]: string }; + @Input() nzBodyStyle: { [key: string]: string }; @Input() nzCover: TemplateRef; @Input() nzActions: Array> = []; @Input() nzType: string; diff --git a/components/card/nz-card.module.ts b/components/card/nz-card.module.ts index 5fccd37ee19..b2ad7ef7529 100644 --- a/components/card/nz-card.module.ts +++ b/components/card/nz-card.module.ts @@ -9,9 +9,8 @@ import { NzCardTabComponent } from './nz-card-tab.component'; import { NzCardComponent } from './nz-card.component'; @NgModule({ - imports : [ CommonModule, NzAddOnModule ], - declarations: [ NzCardComponent, NzCardGridDirective, NzCardMetaComponent, NzCardLoadingComponent, NzCardTabComponent ], - exports : [ NzCardComponent, NzCardGridDirective, NzCardMetaComponent, NzCardLoadingComponent, NzCardTabComponent ] + imports: [CommonModule, NzAddOnModule], + declarations: [NzCardComponent, NzCardGridDirective, NzCardMetaComponent, NzCardLoadingComponent, NzCardTabComponent], + exports: [NzCardComponent, NzCardGridDirective, NzCardMetaComponent, NzCardLoadingComponent, NzCardTabComponent] }) -export class NzCardModule { -} +export class NzCardModule {} diff --git a/components/card/nz-card.spec.ts b/components/card/nz-card.spec.ts index 690e2e7c8c8..834d7b744d3 100644 --- a/components/card/nz-card.spec.ts +++ b/components/card/nz-card.spec.ts @@ -19,8 +19,8 @@ import { NzCardModule } from './nz-card.module'; describe('card', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzCardModule ], - schemas : [ NO_ERRORS_SCHEMA ], + imports: [NzCardModule], + schemas: [NO_ERRORS_SCHEMA], declarations: [ NzDemoCardBasicComponent, NzDemoCardBorderLessComponent, @@ -97,10 +97,10 @@ describe('card', () => { const fixture = TestBed.createComponent(NzDemoCardTabsComponent); const cards = fixture.debugElement.queryAll(By.directive(NzCardComponent)); fixture.detectChanges(); - expect(cards[ 0 ].nativeElement.classList).toContain('ant-card-contain-tabs'); - expect(cards[ 0 ].nativeElement.firstElementChild.firstElementChild!.classList).toContain('ant-card-head-wrapper'); - expect(cards[ 1 ].nativeElement.classList).toContain('ant-card-contain-tabs'); - expect(cards[ 1 ].nativeElement.firstElementChild.firstElementChild!.classList).toContain('ant-card-head-wrapper'); + expect(cards[0].nativeElement.classList).toContain('ant-card-contain-tabs'); + expect(cards[0].nativeElement.firstElementChild.firstElementChild!.classList).toContain('ant-card-head-wrapper'); + expect(cards[1].nativeElement.classList).toContain('ant-card-contain-tabs'); + expect(cards[1].nativeElement.firstElementChild.firstElementChild!.classList).toContain('ant-card-head-wrapper'); }); it('should meta work', () => { const fixture = TestBed.createComponent(NzDemoCardMetaComponent); diff --git a/components/carousel/demo/autoplay.ts b/components/carousel/demo/autoplay.ts index 5d1c43492e4..db6cb36c304 100644 --- a/components/carousel/demo/autoplay.ts +++ b/components/carousel/demo/autoplay.ts @@ -4,24 +4,28 @@ import { Component } from '@angular/core'; selector: 'nz-demo-carousel-autoplay', template: ` -

{{index}}

-
`, - styles : [ - `[nz-carousel-content] { - text-align: center; - height: 160px; - line-height: 160px; - background: #364d79; - color: #fff; - overflow: hidden; - } +
+

{{ index }}

+
+ + `, + styles: [ + ` + [nz-carousel-content] { + text-align: center; + height: 160px; + line-height: 160px; + background: #364d79; + color: #fff; + overflow: hidden; + } - h3 { - color: #fff; - } + h3 { + color: #fff; + } ` ] }) export class NzDemoCarouselAutoplayComponent { - array = [ 1, 2, 3, 4 ]; + array = [1, 2, 3, 4]; } diff --git a/components/carousel/demo/basic.ts b/components/carousel/demo/basic.ts index dab1a7be81c..0638c60e2ad 100644 --- a/components/carousel/demo/basic.ts +++ b/components/carousel/demo/basic.ts @@ -4,25 +4,29 @@ import { Component } from '@angular/core'; selector: 'nz-demo-carousel-basic', template: ` -

{{index}}

-
`, - styles : [ - `[nz-carousel-content] { - text-align: center; - height: 160px; - line-height: 160px; - background: #364d79; - color: #fff; - overflow: hidden; - } +
+

{{ index }}

+
+ + `, + styles: [ + ` + [nz-carousel-content] { + text-align: center; + height: 160px; + line-height: 160px; + background: #364d79; + color: #fff; + overflow: hidden; + } - h3 { - color: #fff; - } + h3 { + color: #fff; + } ` ] }) export class NzDemoCarouselBasicComponent { - array = [ 1, 2, 3, 4 ]; + array = [1, 2, 3, 4]; effect = 'scrollx'; } diff --git a/components/carousel/demo/fade.ts b/components/carousel/demo/fade.ts index 6f58f7e845b..f631f9e2f89 100644 --- a/components/carousel/demo/fade.ts +++ b/components/carousel/demo/fade.ts @@ -4,24 +4,28 @@ import { Component } from '@angular/core'; selector: 'nz-demo-carousel-fade', template: ` -

{{index}}

-
`, - styles : [ - `[nz-carousel-content] { - text-align: center; - height: 160px; - line-height: 160px; - background: #364d79; - color: #fff; - overflow: hidden; - } +
+

{{ index }}

+
+ + `, + styles: [ + ` + [nz-carousel-content] { + text-align: center; + height: 160px; + line-height: 160px; + background: #364d79; + color: #fff; + overflow: hidden; + } - h3 { - color: #fff; - } + h3 { + color: #fff; + } ` ] }) export class NzDemoCarouselFadeComponent { - array = [ 1, 2, 3, 4 ]; + array = [1, 2, 3, 4]; } diff --git a/components/carousel/demo/vertical.ts b/components/carousel/demo/vertical.ts index 7e6588a211b..3c7788deb72 100644 --- a/components/carousel/demo/vertical.ts +++ b/components/carousel/demo/vertical.ts @@ -4,24 +4,28 @@ import { Component } from '@angular/core'; selector: 'nz-demo-carousel-vertical', template: ` -

{{index}}

-
`, - styles : [ - `[nz-carousel-content] { - text-align: center; - height: 160px; - line-height: 160px; - background: #364d79; - color: #fff; - overflow: hidden; - } +
+

{{ index }}

+
+ + `, + styles: [ + ` + [nz-carousel-content] { + text-align: center; + height: 160px; + line-height: 160px; + background: #364d79; + color: #fff; + overflow: hidden; + } - h3 { - color: #fff; - } + h3 { + color: #fff; + } ` ] }) export class NzDemoCarouselVerticalComponent { - array = [ 1, 2, 3 ]; + array = [1, 2, 3]; } diff --git a/components/carousel/nz-carousel-content.directive.ts b/components/carousel/nz-carousel-content.directive.ts index 1c99459ba02..9c191c3cd7e 100755 --- a/components/carousel/nz-carousel-content.directive.ts +++ b/components/carousel/nz-carousel-content.directive.ts @@ -1,9 +1,4 @@ -import { - Directive, - ElementRef, - OnInit, - Renderer2 -} from '@angular/core'; +import { Directive, ElementRef, OnInit, Renderer2 } from '@angular/core'; import { isNotNil } from '../core/util/check'; diff --git a/components/carousel/nz-carousel.component.ts b/components/carousel/nz-carousel.component.ts index 28fb16d4543..0e358cfb1ef 100755 --- a/components/carousel/nz-carousel.component.ts +++ b/components/carousel/nz-carousel.component.ts @@ -30,16 +30,16 @@ export type NzCarouselEffects = 'fade' | 'scrollx'; export type SwipeDirection = 'swipeleft' | 'swiperight'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-carousel', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-carousel', preserveWhitespaces: false, - templateUrl : './nz-carousel.component.html', - host : { + templateUrl: './nz-carousel.component.html', + host: { '[class.ant-carousel-vertical]': 'nzVertical' }, - styles : [ - ` + styles: [ + ` nz-carousel { display: block; position: relative; @@ -88,14 +88,19 @@ export class NzCarouselComponent implements AfterViewInit, AfterContentInit, OnD private subs_ = new Subscription(); get nextIndex(): number { - return this.activeIndex < this.slideContents.length - 1 ? (this.activeIndex + 1) : 0; + return this.activeIndex < this.slideContents.length - 1 ? this.activeIndex + 1 : 0; } get prevIndex(): number { - return this.activeIndex > 0 ? (this.activeIndex - 1) : (this.slideContents.length - 1); + return this.activeIndex > 0 ? this.activeIndex - 1 : this.slideContents.length - 1; } - constructor(public elementRef: ElementRef, private renderer: Renderer2, private cdr: ChangeDetectorRef, private ngZone: NgZone) { + constructor( + public elementRef: ElementRef, + private renderer: Renderer2, + private cdr: ChangeDetectorRef, + private ngZone: NgZone + ) { renderer.addClass(elementRef.nativeElement, 'ant-carousel'); } @@ -107,15 +112,21 @@ export class NzCarouselComponent implements AfterViewInit, AfterContentInit, OnD ngAfterViewInit(): void { // Re-render when content changes. - this.subs_.add(this.slideContents.changes.subscribe(() => { - this.renderContent(); - })); + this.subs_.add( + this.slideContents.changes.subscribe(() => { + this.renderContent(); + }) + ); this.ngZone.runOutsideAngular(() => { - this.subs_.add(fromEvent(window, 'resize').pipe(debounceTime(50)).subscribe(() => { - this.renderContent(); - this.setTransition(); - })); + this.subs_.add( + fromEvent(window, 'resize') + .pipe(debounceTime(50)) + .subscribe(() => { + this.renderContent(); + this.setTransition(); + }) + ); }); // When used in modals (drawers maybe too), it should render itself asynchronously. @@ -144,7 +155,7 @@ export class NzCarouselComponent implements AfterViewInit, AfterContentInit, OnD this.nzBeforeChange.emit({ from: this.slideContents.toArray().findIndex(slide => slide.isActive), to: index }); this.activeIndex = index; this.setTransition(); - this.slideContents.forEach((slide, i) => slide.isActive = index === i); + this.slideContents.forEach((slide, i) => (slide.isActive = index === i)); this.setUpNextScroll(); this.cdr.markForCheck(); // Should trigger the following when animation is done. The transition takes 0.5 seconds according to the CSS. @@ -153,11 +164,12 @@ export class NzCarouselComponent implements AfterViewInit, AfterContentInit, OnD } private setTransition(): void { - this.transform = this.nzEffect === 'fade' - ? 'translate3d(0px, 0px, 0px)' - : this.nzVertical - // `Scrollx` mode. - ? `translate3d(0px, ${-this.activeIndex * this.el.offsetHeight}px, 0px)` + this.transform = + this.nzEffect === 'fade' + ? 'translate3d(0px, 0px, 0px)' + : this.nzVertical + ? // `Scrollx` mode. + `translate3d(0px, ${-this.activeIndex * this.el.offsetHeight}px, 0px)` : `translate3d(${-this.activeIndex * this.el.offsetWidth}px, 0px, 0px)`; if (this.slickTrack) { this.renderer.setStyle(this.slickTrack.nativeElement, 'transform', this.transform); @@ -179,10 +191,12 @@ export class NzCarouselComponent implements AfterViewInit, AfterContentInit, OnD } onKeyDown(e: KeyboardEvent): void { - if (e.keyCode === LEFT_ARROW) { // Left + if (e.keyCode === LEFT_ARROW) { + // Left this.pre(); e.preventDefault(); - } else if (e.keyCode === RIGHT_ARROW) { // Right + } else if (e.keyCode === RIGHT_ARROW) { + // Right this.next(); e.preventDefault(); } diff --git a/components/carousel/nz-carousel.module.ts b/components/carousel/nz-carousel.module.ts index bc2e1c019a1..d21b8ea7367 100644 --- a/components/carousel/nz-carousel.module.ts +++ b/components/carousel/nz-carousel.module.ts @@ -5,9 +5,8 @@ import { NzCarouselContentDirective } from './nz-carousel-content.directive'; import { NzCarouselComponent } from './nz-carousel.component'; @NgModule({ - declarations: [ NzCarouselComponent, NzCarouselContentDirective ], - exports : [ NzCarouselComponent, NzCarouselContentDirective ], - imports : [ CommonModule ] + declarations: [NzCarouselComponent, NzCarouselContentDirective], + exports: [NzCarouselComponent, NzCarouselContentDirective], + imports: [CommonModule] }) -export class NzCarouselModule { -} +export class NzCarouselModule {} diff --git a/components/carousel/nz-carousel.spec.ts b/components/carousel/nz-carousel.spec.ts index 5aec779aeb4..e0c522b8f4b 100644 --- a/components/carousel/nz-carousel.spec.ts +++ b/components/carousel/nz-carousel.spec.ts @@ -12,8 +12,8 @@ import { NzCarouselModule } from './nz-carousel.module'; describe('carousel', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzCarouselModule ], - declarations: [ NzTestCarouselBasicComponent ] + imports: [NzCarouselModule], + declarations: [NzTestCarouselBasicComponent] }); TestBed.compileComponents(); })); @@ -33,7 +33,7 @@ describe('carousel', () => { fixture.detectChanges(); expect(carouselWrapper.nativeElement.classList).toContain('ant-carousel'); expect(carouselContents.every(content => content.nativeElement.classList.contains('slick-slide'))).toBe(true); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); }); it('should dynamic change content work', fakeAsync(() => { fixture.detectChanges(); @@ -61,31 +61,33 @@ describe('carousel', () => { expect(carouselWrapper.nativeElement.querySelector('.slick-dots').children.length).toBe(4); expect(carouselWrapper.nativeElement.querySelector('.slick-dots').firstElementChild.innerText).toBe('1'); expect(carouselWrapper.nativeElement.querySelector('.slick-dots').lastElementChild.innerText).toBe('4'); - expect(carouselWrapper.nativeElement.querySelector('.slick-dots').firstElementChild.firstElementChild.tagName).toBe('A'); + expect( + carouselWrapper.nativeElement.querySelector('.slick-dots').firstElementChild.firstElementChild.tagName + ).toBe('A'); }); it('should click content change', () => { fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); carouselWrapper.nativeElement.querySelector('.slick-dots').lastElementChild.click(); fixture.detectChanges(); - expect(carouselContents[ 3 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[3].nativeElement.classList).toContain('slick-active'); }); it('should keydown change content work', () => { fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); const list = carouselWrapper.nativeElement.querySelector('.slick-list'); dispatchKeyboardEvent(list, 'keydown', LEFT_ARROW); fixture.detectChanges(); - expect(carouselContents[ 3 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[3].nativeElement.classList).toContain('slick-active'); dispatchKeyboardEvent(list, 'keydown', LEFT_ARROW); fixture.detectChanges(); - expect(carouselContents[ 2 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[2].nativeElement.classList).toContain('slick-active'); dispatchKeyboardEvent(list, 'keydown', RIGHT_ARROW); fixture.detectChanges(); - expect(carouselContents[ 3 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[3].nativeElement.classList).toContain('slick-active'); dispatchKeyboardEvent(list, 'keydown', RIGHT_ARROW); fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); }); it('should vertical work', () => { fixture.detectChanges(); @@ -107,59 +109,63 @@ describe('carousel', () => { testComponent.effect = 'fade'; testComponent.vertical = true; fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); carouselWrapper.nativeElement.querySelector('.slick-dots').lastElementChild.click(); fixture.detectChanges(); - expect(carouselWrapper.nativeElement.querySelector('.slick-track').style.transform).toBe('translate3d(0px, 0px, 0px)'); + expect(carouselWrapper.nativeElement.querySelector('.slick-track').style.transform).toBe( + 'translate3d(0px, 0px, 0px)' + ); testComponent.effect = 'scrollx'; fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); carouselWrapper.nativeElement.querySelector('.slick-dots').lastElementChild.click(); fixture.detectChanges(); - expect(carouselWrapper.nativeElement.querySelector('.slick-track').style.transform).not.toBe('translate3d(0px, 0px, 0px)'); + expect(carouselWrapper.nativeElement.querySelector('.slick-track').style.transform).not.toBe( + 'translate3d(0px, 0px, 0px)' + ); }); it('should autoplay work', fakeAsync(() => { testComponent.autoPlay = true; fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); fixture.detectChanges(); tick(5000); fixture.detectChanges(); - expect(carouselContents[ 1 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[1].nativeElement.classList).toContain('slick-active'); carouselWrapper.nativeElement.querySelector('.slick-dots').lastElementChild.click(); fixture.detectChanges(); tick(5000); fixture.detectChanges(); testComponent.nzCarouselComponent.clearTimeout(); // Manually stop the auto play to quit this test. - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); })); it('should autoplay speed work', fakeAsync(() => { testComponent.autoPlay = true; testComponent.autoPlaySpeed = 1000; fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); fixture.detectChanges(); tick(1000 + 10); fixture.detectChanges(); - expect(carouselContents[ 1 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[1].nativeElement.classList).toContain('slick-active'); testComponent.autoPlaySpeed = 0; fixture.detectChanges(); tick(2000 + 10); fixture.detectChanges(); - expect(carouselContents[ 1 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[1].nativeElement.classList).toContain('slick-active'); })); it('should func work', () => { fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); testComponent.nzCarouselComponent.next(); fixture.detectChanges(); - expect(carouselContents[ 1 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[1].nativeElement.classList).toContain('slick-active'); testComponent.nzCarouselComponent.pre(); fixture.detectChanges(); - expect(carouselContents[ 0 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[0].nativeElement.classList).toContain('slick-active'); testComponent.nzCarouselComponent.goTo(2); fixture.detectChanges(); - expect(carouselContents[ 2 ].nativeElement.classList).toContain('slick-active'); + expect(carouselContents[2].nativeElement.classList).toContain('slick-active'); }); it('should resize content after window resized', fakeAsync(() => { // @ts-ignore @@ -198,20 +204,25 @@ describe('carousel', () => { [nzAutoPlay]="autoPlay" [nzAutoPlaySpeed]="autoPlaySpeed" (nzAfterChange)="afterChange($event)" - (nzBeforeChange)="beforeChange($event)"> -

{{index}}

- {{index+1}} - ` + (nzBeforeChange)="beforeChange($event)" + > +
+

{{ index }}

+
+ {{ index + 1 }} + + ` }) export class NzTestCarouselBasicComponent { @ViewChild(NzCarouselComponent) nzCarouselComponent: NzCarouselComponent; dots = true; vertical = false; effect = 'scrollx'; - array = [ 1, 2, 3, 4 ]; + array = [1, 2, 3, 4]; autoPlay = false; autoPlaySpeed = 3000; afterChange = jasmine.createSpy('afterChange callback'); beforeChange = jasmine.createSpy('beforeChange callback'); - } diff --git a/components/cascader/demo/basic.ts b/components/cascader/demo/basic.ts index 27c3e5126af..0a1d26456f8 100644 --- a/components/cascader/demo/basic.ts +++ b/components/cascader/demo/basic.ts @@ -1,85 +1,104 @@ // tslint:disable:no-any import { Component, OnInit } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; -const otherOptions = [{ - value: 'fujian', - label: 'Fujian', - children: [{ - value: 'xiamen', - label: 'Xiamen', - children: [{ - value: 'Kulangsu', - label: 'Kulangsu', - isLeaf: true - }] - }] -}, { - value: 'guangxi', - label: 'Guangxi', - children: [{ - value: 'guilin', - label: 'Guilin', - children: [{ - value: 'Lijiang', - label: 'Li Jiang River', - isLeaf: true - }] - }] -}]; +const otherOptions = [ + { + value: 'fujian', + label: 'Fujian', + children: [ + { + value: 'xiamen', + label: 'Xiamen', + children: [ + { + value: 'Kulangsu', + label: 'Kulangsu', + isLeaf: true + } + ] + } + ] + }, + { + value: 'guangxi', + label: 'Guangxi', + children: [ + { + value: 'guilin', + label: 'Guilin', + children: [ + { + value: 'Lijiang', + label: 'Li Jiang River', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-basic', template: ` - - +   Change Options - `, - styles : [ + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } - .change-options { - display: inline-block; - font-size: 12px; - margin-top: 8px; - } + .ant-cascader-picker { + width: 300px; + } + .change-options { + display: inline-block; + font-size: 12px; + margin-top: 8px; + } ` ] }) @@ -89,7 +108,7 @@ export class NzDemoCascaderBasicComponent implements OnInit { ngOnInit(): void { setTimeout(() => { - this.nzOptions = options; + this.nzOptions = options; }, 100); } diff --git a/components/cascader/demo/change-on-function.ts b/components/cascader/demo/change-on-function.ts index 1982a24b983..864c10a3e25 100644 --- a/components/cascader/demo/change-on-function.ts +++ b/components/cascader/demo/change-on-function.ts @@ -1,39 +1,53 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - children: [{ - value: 'dongqianlake', - label: 'Dongqian Lake', - isLeaf: true - }] - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + children: [ + { + value: 'dongqianlake', + label: 'Dongqian Lake', + isLeaf: true + } + ] + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-change-on-function', @@ -42,13 +56,15 @@ const options = [{ [nzChangeOn]="validate" [nzOptions]="nzOptions" [(ngModel)]="values" - (ngModelChange)="onChanges($event)"> - `, - styles : [ + (ngModelChange)="onChanges($event)" + > + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/change-on-select.ts b/components/cascader/demo/change-on-select.ts index 9fa04f43027..b1fda51c858 100644 --- a/components/cascader/demo/change-on-select.ts +++ b/components/cascader/demo/change-on-select.ts @@ -1,50 +1,59 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-change-on-select', template: ` - - `, - styles : [ + + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/custom-field-names.ts b/components/cascader/demo/custom-field-names.ts index 672adea552b..f673209d903 100644 --- a/components/cascader/demo/custom-field-names.ts +++ b/components/cascader/demo/custom-field-names.ts @@ -1,39 +1,53 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - code: 'zhejiang', - name: 'Zhejiang', - children: [{ - code: 'hangzhou', - name: 'Hangzhou', - children: [{ - code: 'xihu', - name: 'West Lake', - isLeaf: true - }] - }, { - code: 'ningbo', - name: 'Ningbo', - children: [{ - code: 'dongqianlake', - name: 'Dongqian Lake', - isLeaf: true - }] - }] -}, { - code: 'jiangsu', - name: 'Jiangsu', - children: [{ - code: 'nanjing', - name: 'Nanjing', - children: [{ - code: 'zhonghuamen', - name: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + code: 'zhejiang', + name: 'Zhejiang', + children: [ + { + code: 'hangzhou', + name: 'Hangzhou', + children: [ + { + code: 'xihu', + name: 'West Lake', + isLeaf: true + } + ] + }, + { + code: 'ningbo', + name: 'Ningbo', + children: [ + { + code: 'dongqianlake', + name: 'Dongqian Lake', + isLeaf: true + } + ] + } + ] + }, + { + code: 'jiangsu', + name: 'Jiangsu', + children: [ + { + code: 'nanjing', + name: 'Nanjing', + children: [ + { + code: 'zhonghuamen', + name: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-custom-field-names', @@ -45,13 +59,15 @@ const options = [{ [nzValueProperty]="'code'" [nzShowSearch]="true" [(ngModel)]="values" - (ngModelChange)="onChanges($event)"> - `, - styles : [ + (ngModelChange)="onChanges($event)" + > + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/custom-render.ts b/components/cascader/demo/custom-render.ts index 2388aea75c4..9d725c39d58 100644 --- a/components/cascader/demo/custom-render.ts +++ b/components/cascader/demo/custom-render.ts @@ -1,38 +1,50 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - code: 752100, - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - code: '315000', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - code: 453400, - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + code: 752100, + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + code: '315000', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + code: 453400, + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-custom-render', @@ -41,22 +53,26 @@ const options = [{ [nzLabelRender]="renderTpl" [nzOptions]="nzOptions" [(ngModel)]="values" - (ngModelChange)="onChanges($event)"> + (ngModelChange)="onChanges($event)" + > - {{label}} / + {{ label }} / - {{label}} ( {{selectedOptions[i].code}} ) + {{ label }} ( + {{ selectedOptions[i].code }} ) - `, - styles : [ +
+ `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) @@ -71,6 +87,6 @@ export class NzDemoCascaderCustomRenderComponent { handleAreaClick(e: Event, label: string, option: any): void { e.preventDefault(); e.stopPropagation(); - console.log('clicked \"', label, '\"', option); + console.log('clicked "', label, '"', option); } } diff --git a/components/cascader/demo/default-value-and-asyn-options.ts b/components/cascader/demo/default-value-and-asyn-options.ts index 97d77bd3523..5211df470f9 100644 --- a/components/cascader/demo/default-value-and-asyn-options.ts +++ b/components/cascader/demo/default-value-and-asyn-options.ts @@ -1,50 +1,58 @@ // tslint:disable:no-any import { Component, OnInit } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-default-value-and-asyn-options', template: ` - - + `, - styles : [ + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) @@ -61,5 +69,4 @@ export class NzDemoCascaderDefaultValueAndAsynOptionsComponent implements OnInit this.nzOptions = options; }, 500); } - } diff --git a/components/cascader/demo/default-value-and-lazyload.ts b/components/cascader/demo/default-value-and-lazyload.ts index b1a1425ae82..abbc8d5bf5b 100644 --- a/components/cascader/demo/default-value-and-lazyload.ts +++ b/components/cascader/demo/default-value-and-lazyload.ts @@ -1,56 +1,64 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const provinces = [{ - value: 'zhejiang', - label: 'Zhejiang' -}, { - value: 'jiangsu', - label: 'Jiangsu' -}]; +const provinces = [ + { + value: 'zhejiang', + label: 'Zhejiang' + }, + { + value: 'jiangsu', + label: 'Jiangsu' + } +]; -const cities: { [ key: string ]: Array<{ value: string, label: string, isLeaf?: boolean }> } = { - zhejiang: [{ - value: 'hangzhou', - label: 'Hangzhou' - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }], - jiangsu: [{ - value: 'nanjing', - label: 'Nanjing' - }] +const cities: { [key: string]: Array<{ value: string; label: string; isLeaf?: boolean }> } = { + zhejiang: [ + { + value: 'hangzhou', + label: 'Hangzhou' + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ], + jiangsu: [ + { + value: 'nanjing', + label: 'Nanjing' + } + ] }; -const scenicspots: { [ key: string ]: Array<{ value: string, label: string, isLeaf?: boolean }> } = { - hangzhou: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }], - nanjing: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] +const scenicspots: { [key: string]: Array<{ value: string; label: string; isLeaf?: boolean }> } = { + hangzhou: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ], + nanjing: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] }; @Component({ selector: 'nz-demo-cascader-default-value-and-lazyload', template: ` - - + `, - styles : [ + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) @@ -63,9 +71,10 @@ export class NzDemoCascaderDefaultValueAndLazyloadComponent { /** load data async execute by `nzLoadData` method */ loadData(node: any, index: number): PromiseLike { - return new Promise((resolve) => { + return new Promise(resolve => { setTimeout(() => { - if (index < 0) { // if index less than 0 it is root node + if (index < 0) { + // if index less than 0 it is root node node.children = provinces; } else if (index === 0) { node.children = cities[node.value]; diff --git a/components/cascader/demo/default-value.ts b/components/cascader/demo/default-value.ts index 9b2fbe7dbfa..d0bb2773c88 100644 --- a/components/cascader/demo/default-value.ts +++ b/components/cascader/demo/default-value.ts @@ -1,50 +1,58 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-default-value', template: ` - - + `, - styles : [ + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/disabled.ts b/components/cascader/demo/disabled.ts index 4cebd093a3b..db0b191f619 100644 --- a/components/cascader/demo/disabled.ts +++ b/components/cascader/demo/disabled.ts @@ -1,50 +1,59 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - disabled: true, - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + disabled: true, + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-disabled', template: ` - - `, - styles : [ + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/hover.ts b/components/cascader/demo/hover.ts index 6e8a4308d1c..995ec6551be 100644 --- a/components/cascader/demo/hover.ts +++ b/components/cascader/demo/hover.ts @@ -1,35 +1,47 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-hover', @@ -38,15 +50,17 @@ const options = [{ [nzExpandTrigger]="'hover'" [nzOptions]="nzOptions" [(ngModel)]="values" - (ngModelChange)="onChanges($event)"> - `, - styles : [ - ` + (ngModelChange)="onChanges($event)" + > + + `, + styles: [ + ` .ant-cascader-picker { width: 300px; } - ` - ] + ` + ] }) export class NzDemoCascaderHoverComponent { nzOptions = options; diff --git a/components/cascader/demo/lazy.ts b/components/cascader/demo/lazy.ts index e5c0fb41a85..d71e63acba3 100644 --- a/components/cascader/demo/lazy.ts +++ b/components/cascader/demo/lazy.ts @@ -1,56 +1,64 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const provinces = [{ - value: 'zhejiang', - label: 'Zhejiang' -}, { - value: 'jiangsu', - label: 'Jiangsu' -}]; +const provinces = [ + { + value: 'zhejiang', + label: 'Zhejiang' + }, + { + value: 'jiangsu', + label: 'Jiangsu' + } +]; -const cities: { [ key: string ]: Array<{ value: string, label: string, isLeaf?: boolean }> } = { - zhejiang: [{ - value: 'hangzhou', - label: 'Hangzhou' - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }], - jiangsu: [{ - value: 'nanjing', - label: 'Nanjing' - }] +const cities: { [key: string]: Array<{ value: string; label: string; isLeaf?: boolean }> } = { + zhejiang: [ + { + value: 'hangzhou', + label: 'Hangzhou' + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ], + jiangsu: [ + { + value: 'nanjing', + label: 'Nanjing' + } + ] }; -const scenicspots: { [ key: string ]: Array<{ value: string, label: string, isLeaf?: boolean }> } = { - hangzhou: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }], - nanjing: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] +const scenicspots: { [key: string]: Array<{ value: string; label: string; isLeaf?: boolean }> } = { + hangzhou: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ], + nanjing: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] }; @Component({ selector: 'nz-demo-cascader-lazy', template: ` - - + `, - styles : [ + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) @@ -63,9 +71,10 @@ export class NzDemoCascaderLazyComponent { /** load data async execute by `nzLoadData` method */ loadData(node: any, index: number): PromiseLike { - return new Promise((resolve) => { + return new Promise(resolve => { setTimeout(() => { - if (index < 0) { // if index less than 0 it is root node + if (index < 0) { + // if index less than 0 it is root node node.children = provinces; } else if (index === 0) { node.children = cities[node.value]; diff --git a/components/cascader/demo/modal.ts b/components/cascader/demo/modal.ts index 01e63b6dda6..ec001d8bb8a 100644 --- a/components/cascader/demo/modal.ts +++ b/components/cascader/demo/modal.ts @@ -1,54 +1,67 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-modal', template: ` - - - + + - `, - styles : [ + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/reactive-form.ts b/components/cascader/demo/reactive-form.ts index 7d92b6d8829..22a0e67c0a9 100644 --- a/components/cascader/demo/reactive-form.ts +++ b/components/cascader/demo/reactive-form.ts @@ -2,52 +2,60 @@ import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; -const options = [ { - value : 'zhejiang', - label : 'Zhejiang', - children: [ { - value : 'hangzhou', - label : 'Hangzhou', - children: [ { - value : 'xihu', - label : 'West Lake', - isLeaf: true - } ] - }, { - value : 'ningbo', - label : 'Ningbo', - isLeaf: true - } ] -}, { - value : 'jiangsu', - label : 'Jiangsu', - children: [ { - value : 'nanjing', - label : 'Nanjing', - children: [ { - value : 'zhonghuamen', - label : 'Zhong Hua Men', - isLeaf: true - } ] - } ] -} ]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-reactive-form', template: `
- - +
-
+
`, - styles : [ - ` + styles: [ + ` .ant-cascader-picker { width: 300px; } @@ -68,7 +76,7 @@ export class NzDemoCascaderReactiveFormComponent { private createForm(): void { this.form = this.fb.group({ - name: [ null, Validators.required ] + name: [null, Validators.required] }); } diff --git a/components/cascader/demo/search.ts b/components/cascader/demo/search.ts index df4bdc0f0ca..eeab91499c2 100644 --- a/components/cascader/demo/search.ts +++ b/components/cascader/demo/search.ts @@ -1,87 +1,106 @@ // tslint:disable:no-any import { Component, OnInit } from '@angular/core'; -const options = [ { - value: 'zhejiang', - label: 'Zhejiang', - children: [ { - value: 'hangzhou', - label: 'Hangzhou', - children: [ { - value: 'xihu', - label: 'West Lake', - isLeaf: true - } ] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true, - disabled: true - } ] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [ { - value: 'nanjing', - label: 'Nanjing', - children: [ { - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - } ] - } ] -} ]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true, + disabled: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; -const otherOptions = [ { - value: 'fujian', - label: 'Fujian', - children: [ { - value: 'xiamen', - label: 'Xiamen', - children: [ { - value: 'Kulangsu', - label: 'Kulangsu', - isLeaf: true - } ] - } ] -}, { - value: 'guangxi', - label: 'Guangxi', - children: [ { - value: 'guilin', - label: 'Guilin', - children: [ { - value: 'Lijiang', - label: 'Li Jiang River', - isLeaf: true - } ] - } ] -} ]; +const otherOptions = [ + { + value: 'fujian', + label: 'Fujian', + children: [ + { + value: 'xiamen', + label: 'Xiamen', + children: [ + { + value: 'Kulangsu', + label: 'Kulangsu', + isLeaf: true + } + ] + } + ] + }, + { + value: 'guangxi', + label: 'Guangxi', + children: [ + { + value: 'guilin', + label: 'Guilin', + children: [ + { + value: 'Lijiang', + label: 'Li Jiang River', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-search', template: ` - +   Change Options - `, + `, styles: [ ` - .ant-cascader-picker { - width: 300px; - } - .change-options { - display: inline-block; - font-size: 12px; - margin-top: 8px; - } + .ant-cascader-picker { + width: 300px; + } + .change-options { + display: inline-block; + font-size: 12px; + margin-top: 8px; + } ` ] }) diff --git a/components/cascader/demo/size.ts b/components/cascader/demo/size.ts index 5210518928b..5915a3fd77f 100644 --- a/components/cascader/demo/size.ts +++ b/components/cascader/demo/size.ts @@ -1,63 +1,63 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-size', template: ` - - - + - + + `, - styles : [ + styles: [ ` - .ant-cascader-picker { - width: 300px; - margin-bottom: 8px; - } + .ant-cascader-picker { + width: 300px; + margin-bottom: 8px; + } ` ] }) diff --git a/components/cascader/demo/trigger-action.ts b/components/cascader/demo/trigger-action.ts index 17304bcfc5e..2e747d27159 100644 --- a/components/cascader/demo/trigger-action.ts +++ b/components/cascader/demo/trigger-action.ts @@ -1,35 +1,47 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-trigger-action', @@ -41,12 +53,13 @@ const options = [{ [(ngModel)]="values" (ngModelChange)="onChanges($event)" > - `, - styles : [ + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/demo/trigger.ts b/components/cascader/demo/trigger.ts index 94251c13c2e..5fdc29f1a9e 100644 --- a/components/cascader/demo/trigger.ts +++ b/components/cascader/demo/trigger.ts @@ -1,54 +1,67 @@ // tslint:disable:no-any import { Component } from '@angular/core'; -const options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] -}, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] -}]; +const options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; @Component({ selector: 'nz-demo-cascader-trigger', template: ` - {{text}} + {{ text }} + > Change city - `, - styles : [ + + `, + styles: [ ` - .ant-cascader-picker { - width: 300px; - } + .ant-cascader-picker { + width: 300px; + } ` ] }) diff --git a/components/cascader/nz-cascader-li.component.ts b/components/cascader/nz-cascader-li.component.ts index e99383277ae..cb22f0d4f33 100644 --- a/components/cascader/nz-cascader-li.component.ts +++ b/components/cascader/nz-cascader-li.component.ts @@ -3,7 +3,8 @@ import { ChangeDetectorRef, Component, ElementRef, - Input, Renderer2, + Input, + Renderer2, SecurityContext, ViewEncapsulation } from '@angular/core'; @@ -12,13 +13,13 @@ import { CascaderOption } from './types'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : '[nz-cascader-option]', - templateUrl : './nz-cascader-li.component.html', - host : { - '[attr.title]' : 'option.title || getOptionLabel()', - '[class.ant-cascader-menu-item-active]' : 'activated', - '[class.ant-cascader-menu-item-expand]' : '!option.isLeaf', + encapsulation: ViewEncapsulation.None, + selector: '[nz-cascader-option]', + templateUrl: './nz-cascader-li.component.html', + host: { + '[attr.title]': 'option.title || getOptionLabel()', + '[class.ant-cascader-menu-item-active]': 'activated', + '[class.ant-cascader-menu-item-expand]': '!option.isLeaf', '[class.ant-cascader-menu-item-disabled]': 'option.disabled' } }) @@ -28,16 +29,24 @@ export class NzCascaderOptionComponent { @Input() highlightText: string; @Input() nzLabelProperty = 'label'; - constructor(private sanitizer: DomSanitizer, private cdr: ChangeDetectorRef, elementRef: ElementRef, renderer: Renderer2) { + constructor( + private sanitizer: DomSanitizer, + private cdr: ChangeDetectorRef, + elementRef: ElementRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-cascader-menu-item'); } getOptionLabel(): string { - return this.option ? this.option[ this.nzLabelProperty ] : ''; + return this.option ? this.option[this.nzLabelProperty] : ''; } renderHighlightString(str: string): string { - const safeHtml = this.sanitizer.sanitize(SecurityContext.HTML, `${this.highlightText}`); + const safeHtml = this.sanitizer.sanitize( + SecurityContext.HTML, + `${this.highlightText}` + ); if (!safeHtml) { throw new Error(`[NG-ZORRO] Input value "${this.highlightText}" is not considered security.`); } diff --git a/components/cascader/nz-cascader.component.ts b/components/cascader/nz-cascader.component.ts index 147f9281429..e51ca3e6c2e 100644 --- a/components/cascader/nz-cascader.component.ts +++ b/components/cascader/nz-cascader.component.ts @@ -45,38 +45,40 @@ import { const defaultDisplayRender = (labels: string[]) => labels.join(' / '); @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-cascader,[nz-cascader]', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-cascader,[nz-cascader]', preserveWhitespaces: false, - templateUrl : './nz-cascader.component.html', - animations : [ slideMotion ], - providers : [ + templateUrl: './nz-cascader.component.html', + animations: [slideMotion], + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzCascaderComponent), - multi : true + multi: true } ], - host : { - '[attr.tabIndex]' : '"0"', - '[class.ant-cascader-lg]' : 'nzSize === "large"', - '[class.ant-cascader-sm]' : 'nzSize === "small"', - '[class.ant-cascader-picker-disabled]' : 'nzDisabled', - '[class.ant-cascader-picker-open]' : 'menuVisible', + host: { + '[attr.tabIndex]': '"0"', + '[class.ant-cascader-lg]': 'nzSize === "large"', + '[class.ant-cascader-sm]': 'nzSize === "small"', + '[class.ant-cascader-picker-disabled]': 'nzDisabled', + '[class.ant-cascader-picker-open]': 'menuVisible', '[class.ant-cascader-picker-with-value]': '!!inputValue', - '[class.ant-cascader-focused]' : 'isFocused' + '[class.ant-cascader-focused]': 'isFocused' }, - styles : [ ` - .ant-cascader-menus { - margin-top: 4px; - margin-bottom: 4px; - top: 100%; - left: 0; - position: relative; - width: 100%; - } - ` ] + styles: [ + ` + .ant-cascader-menus { + margin-top: 4px; + margin-bottom: 4px; + top: 100%; + left: 0; + position: relative; + width: 100%; + } + ` + ] }) export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { @ViewChild('input') input: ElementRef; @@ -100,10 +102,10 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { @Input() nzShowSearch: boolean | NzShowSearchOptions; @Input() nzPlaceHolder = 'Please select'; @Input() nzMenuClassName: string; - @Input() nzMenuStyle: { [ key: string ]: string; }; + @Input() nzMenuStyle: { [key: string]: string }; @Input() nzMouseEnterDelay: number = 150; // ms @Input() nzMouseLeaveDelay: number = 150; // ms - @Input() nzTriggerAction: NzCascaderTriggerType | NzCascaderTriggerType[] = [ 'click' ] as NzCascaderTriggerType[]; + @Input() nzTriggerAction: NzCascaderTriggerType | NzCascaderTriggerType[] = ['click'] as NzCascaderTriggerType[]; @Input() nzChangeOn: (option: CascaderOption, level: number) => boolean; // tslint:disable-next-line:no-any @@ -111,11 +113,11 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { @Input() get nzOptions(): CascaderOption[] | null { - return this.columns[ 0 ]; + return this.columns[0]; } set nzOptions(options: CascaderOption[] | null) { - this.columnsSnapshot = this.columns = options && options.length ? [ options ] : []; + this.columnsSnapshot = this.columns = options && options.length ? [options] : []; if (!this.isSearching) { if (this.defaultValue && this.columns.length) { this.initOptions(0); @@ -126,7 +128,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { } @Output() readonly nzSelectionChange = new EventEmitter(); - @Output() readonly nzSelect = new EventEmitter<{ option: CascaderOption, index: number }>(); + @Output() readonly nzSelect = new EventEmitter<{ option: CascaderOption; index: number }>(); @Output() readonly nzClear = new EventEmitter(); @Output() readonly nzVisibleChange = new EventEmitter(); // Not exposed, only for test @Output() readonly nzChange = new EventEmitter(); // Not exposed, only for test @@ -140,7 +142,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { columns: CascaderOption[][] = []; onChange = Function.prototype; onTouched = Function.prototype; - positions: ConnectionPositionPair[] = [ ...DEFAULT_CASCADER_POSITIONS ]; + positions: ConnectionPositionPair[] = [...DEFAULT_CASCADER_POSITIONS]; dropdownWidthStyle: string; isSearching = false; isFocused = false; @@ -168,13 +170,13 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { get menuCls(): NgClassType { return { - [ `${this.nzMenuClassName}` ]: !!this.nzMenuClassName + [`${this.nzMenuClassName}`]: !!this.nzMenuClassName }; } get menuColumnCls(): NgClassType { return { - [ `${this.nzColumnClassName}` ]: !!this.nzColumnClassName + [`${this.nzColumnClassName}`]: !!this.nzColumnClassName }; } @@ -235,11 +237,11 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { //#region Init private isLoaded(index: number): boolean { - return this.columns[ index ] && this.columns[ index ].length > 0; + return this.columns[index] && this.columns[index].length > 0; } private findOption(option: CascaderOption, index: number): CascaderOption | undefined { - const options: CascaderOption[] = this.columns[ index ]; + const options: CascaderOption[] = this.columns[index]; if (options) { const value = typeof option === 'object' ? this.getOptionValue(option) : option; return options.find(o => value === this.getOptionValue(o)); @@ -251,10 +253,13 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { private activateOnInit(index: number, value: any): void { let option = this.findOption(value, index); if (!option) { - option = typeof value === 'object' ? value : { - [ `${this.nzValueProperty}` ]: value, - [ `${this.nzLabelProperty}` ]: value - }; + option = + typeof value === 'object' + ? value + : { + [`${this.nzValueProperty}`]: value, + [`${this.nzLabelProperty}`]: value + }; } this.setOptionActivated(option!, index, false, false); } @@ -264,7 +269,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { const lastIndex = vs.length - 1; const load = () => { - this.activateOnInit(index, vs[ index ]); + this.activateOnInit(index, vs[index]); if (index < lastIndex) { this.initOptions(index + 1); } @@ -276,7 +281,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { if (this.isLoaded(index) || !this.nzLoadData) { load(); } else { - const node = this.activatedOptions[ index - 1 ] || {}; + const node = this.activatedOptions[index - 1] || {}; this.loadChildrenAsync(node, index - 1, load, this.afterWriteValue); } } @@ -285,17 +290,22 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { //#region Mutating data - private setOptionActivated(option: CascaderOption, columnIndex: number, select: boolean = false, loadChildren: boolean = true): void { + private setOptionActivated( + option: CascaderOption, + columnIndex: number, + select: boolean = false, + loadChildren: boolean = true + ): void { if (!option || option.disabled) { return; } - this.activatedOptions[ columnIndex ] = option; + this.activatedOptions[columnIndex] = option; // Set parent option and all ancestor options as active. for (let i = columnIndex - 1; i >= 0; i--) { - if (!this.activatedOptions[ i ]) { - this.activatedOptions[ i ] = this.activatedOptions[ i + 1 ].parent!; + if (!this.activatedOptions[i]) { + this.activatedOptions[i] = this.activatedOptions[i + 1].parent!; } } @@ -306,7 +316,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { // Load child options. if (option.children && option.children.length && !option.isLeaf) { - option.children.forEach(child => child.parent = option); + option.children.forEach(child => (child.parent = option)); this.setColumnData(option.children, columnIndex + 1); } else if (!option.isLeaf && loadChildren) { this.loadChildrenAsync(option, columnIndex); @@ -320,30 +330,38 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { this.reposition(); } - private loadChildrenAsync(option: CascaderOption, columnIndex: number, success?: () => void, failure?: () => void): void { + private loadChildrenAsync( + option: CascaderOption, + columnIndex: number, + success?: () => void, + failure?: () => void + ): void { if (this.nzLoadData) { this.isLoading = columnIndex < 0; option.loading = true; - this.nzLoadData(option, columnIndex).then(() => { - if (option.children) { - option.children.forEach(child => child.parent = columnIndex < 0 ? undefined : option); - this.setColumnData(option.children, columnIndex + 1); + this.nzLoadData(option, columnIndex).then( + () => { + if (option.children) { + option.children.forEach(child => (child.parent = columnIndex < 0 ? undefined : option)); + this.setColumnData(option.children, columnIndex + 1); + } + if (success) { + success(); + } + option.loading = this.isLoading = false; // Need to check children. + this.checkChildren(); + // Reposition in the next tick, because we use markForCheck above. + Promise.resolve().then(() => this.reposition()); + }, + () => { + option.loading = this.isLoading = false; + option.isLeaf = true; + this.cdr.detectChanges(); + if (failure) { + failure(); + } } - if (success) { - success(); - } - option.loading = this.isLoading = false; // Need to check children. - this.checkChildren(); - // Reposition in the next tick, because we use markForCheck above. - Promise.resolve().then(() => this.reposition()); - }, () => { - option.loading = this.isLoading = false; - option.isLeaf = true; - this.cdr.detectChanges(); - if (failure) { - failure(); - } - }); + ); } } @@ -366,8 +384,8 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { } private setColumnData(options: CascaderOption[], columnIndex: number): void { - if (!arraysEqual(this.columns[ columnIndex ], options)) { - this.columns[ columnIndex ] = options; + if (!arraysEqual(this.columns[columnIndex], options)) { + this.columns[columnIndex] = options; if (columnIndex < this.columns.length - 1) { this.columns = this.columns.slice(0, columnIndex + 1); } @@ -446,11 +464,12 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { this.focus(); } - @HostListener('keydown', [ '$event' ]) + @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent): void { const keyCode = event.keyCode; - if (keyCode !== DOWN_ARROW && + if ( + keyCode !== DOWN_ARROW && keyCode !== UP_ARROW && keyCode !== LEFT_ARROW && keyCode !== RIGHT_ARROW && @@ -512,7 +531,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { } } - @HostListener('mouseleave', [ '$event' ]) + @HostListener('mouseleave', ['$event']) onTriggerMouseLeave(event: MouseEvent): void { if (this.nzDisabled) { return; @@ -524,7 +543,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { if (this.isActionTrigger('hover')) { const mouseTarget = event.relatedTarget as HTMLElement; const hostEl = this.el; - const menuEl = this.menu && this.menu.nativeElement as HTMLElement; + const menuEl = this.menu && (this.menu.nativeElement as HTMLElement); if (hostEl.contains(mouseTarget) || (menuEl && menuEl.contains(mouseTarget))) { return; } @@ -553,7 +572,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { private onEnter(): void { const columnIndex = Math.max(this.activatedOptions.length - 1, 0); - const option = this.activatedOptions[ columnIndex ]; + const option = this.activatedOptions[columnIndex]; if (option && !option.disabled) { this.isSearching ? this.setSearchOptionActivated(option as CascaderSearchOption) @@ -563,11 +582,12 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { private moveUpOrDown(isUp: boolean): void { const columnIndex = Math.max(this.activatedOptions.length - 1, 0); - const activeOption = this.activatedOptions[ columnIndex ]; - const options = this.columns[ columnIndex ] || []; + const activeOption = this.activatedOptions[columnIndex]; + const options = this.columns[columnIndex] || []; const length = options.length; let nextIndex = -1; - if (!activeOption) { // Not selected options in this column + if (!activeOption) { + // Not selected options in this column nextIndex = isUp ? length : -1; } else { nextIndex = options.indexOf(activeOption); @@ -578,7 +598,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { if (nextIndex < 0 || nextIndex >= length) { break; } - const nextOption = options[ nextIndex ]; + const nextOption = options[nextIndex]; if (!nextOption || nextOption.disabled) { continue; } @@ -596,7 +616,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { private moveRight(): void { const length = this.activatedOptions.length; - const options = this.columns[ length ]; + const options = this.columns[length]; if (options && options.length) { const nextOpt = options.find(o => !o.disabled); if (nextOpt) { @@ -683,12 +703,13 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { }; const filter: NzCascaderFilterFunction = isNzShowSearchOptions(this.nzShowSearch) && this.nzShowSearch.filter ? this.nzShowSearch.filter : defaultFilter; - const sorter: NzCascaderSorterFunction | undefined = - isNzShowSearchOptions(this.nzShowSearch) ? (this.nzShowSearch as NzShowSearchOptions).sorter : undefined; + const sorter: NzCascaderSorterFunction | undefined = isNzShowSearchOptions(this.nzShowSearch) + ? (this.nzShowSearch as NzShowSearchOptions).sorter + : undefined; const loopParent = (node: CascaderOption, forceDisabled = false) => { const disabled = forceDisabled || node.disabled; path.push(node); - node.children!.forEach((sNode) => { + node.children!.forEach(sNode => { if (!sNode.parent) { sNode.parent = node; } // Build parent reference when doing searching @@ -708,9 +729,9 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { const disabled = forceDisabled || node.disabled; const option: CascaderSearchOption = { disabled, - isLeaf : true, - path : cPath, - [ this.nzLabelProperty ]: cPath.map(p => this.getOptionLabel(p)).join(' / ') + isLeaf: true, + path: cPath, + [this.nzLabelProperty]: cPath.map(p => this.getOptionLabel(p)).join(' / ') }; results.push(option); } @@ -718,28 +739,29 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { }; if (!this.columnsSnapshot.length) { - this.columns = [ [] ]; + this.columns = [[]]; return; } - this.columnsSnapshot[ 0 ].forEach(node => (node.isLeaf || !node.children || !node.children.length) - ? loopChild(node) - : loopParent(node) + this.columnsSnapshot[0].forEach(node => + node.isLeaf || !node.children || !node.children.length ? loopChild(node) : loopParent(node) ); - if (sorter) { results.sort((a, b) => sorter(a.path, b.path, this._inputValue)); } + if (sorter) { + results.sort((a, b) => sorter(a.path, b.path, this._inputValue)); + } - this.columns = [ results ]; + this.columns = [results]; } setSearchOptionActivated(result: CascaderSearchOption, event?: Event): void { - this.activatedOptions = [ result ]; + this.activatedOptions = [result]; this.delaySetMenuVisible(false, 200); setTimeout(() => { this.inputValue = ''; const index = result.path.length - 1; - const destinationNode = result.path[ index ]; + const destinationNode = result.path[index]; // NOTE: optimize this. const mockClickParent = (node: CascaderOption, columnIndex: number) => { if (node && node.parent) { @@ -777,16 +799,16 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { // tslint:disable-next-line:no-any getOptionLabel(option: CascaderOption): any { - return option[ this.nzLabelProperty || 'label' ]; + return option[this.nzLabelProperty || 'label']; } // tslint:disable-next-line:no-any getOptionValue(option: CascaderOption): any { - return option[ this.nzValueProperty || 'value' ]; + return option[this.nzValueProperty || 'value']; } isOptionActivated(option: CascaderOption, index: number): boolean { - const activeOpt = this.activatedOptions[ index ]; + const activeOpt = this.activatedOptions[index]; return activeOpt === option; } @@ -817,8 +839,12 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { this.setMenuVisible(false); } - constructor(private elementRef: ElementRef, private cdr: ChangeDetectorRef, renderer: Renderer2, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + private elementRef: ElementRef, + private cdr: ChangeDetectorRef, + renderer: Renderer2, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { renderer.addClass(elementRef.nativeElement, 'ant-cascader'); renderer.addClass(elementRef.nativeElement, 'ant-cascader-picker'); } @@ -838,7 +864,7 @@ export class NzCascaderComponent implements OnDestroy, ControlValueAccessor { // tslint:disable-next-line:no-any writeValue(value: any): void { - const vs = this.defaultValue = toArray(value); + const vs = (this.defaultValue = toArray(value)); if (vs.length) { this.initOptions(0); } else { diff --git a/components/cascader/nz-cascader.module.ts b/components/cascader/nz-cascader.module.ts index ef9b9f16cb0..70c3be1e3bb 100644 --- a/components/cascader/nz-cascader.module.ts +++ b/components/cascader/nz-cascader.module.ts @@ -12,14 +12,17 @@ import { NzCascaderOptionComponent } from './nz-cascader-li.component'; import { NzCascaderComponent } from './nz-cascader.component'; @NgModule({ - imports : [ CommonModule, FormsModule, OverlayModule, NzInputModule, NzIconModule, NzEmptyModule, NzOverlayModule, NzNoAnimationModule ], - declarations: [ - NzCascaderComponent, - NzCascaderOptionComponent + imports: [ + CommonModule, + FormsModule, + OverlayModule, + NzInputModule, + NzIconModule, + NzEmptyModule, + NzOverlayModule, + NzNoAnimationModule ], - exports : [ - NzCascaderComponent - ] + declarations: [NzCascaderComponent, NzCascaderOptionComponent], + exports: [NzCascaderComponent] }) -export class NzCascaderModule { -} +export class NzCascaderModule {} diff --git a/components/cascader/nz-cascader.spec.ts b/components/cascader/nz-cascader.spec.ts index c7fac20df42..aff08e99278 100644 --- a/components/cascader/nz-cascader.spec.ts +++ b/components/cascader/nz-cascader.spec.ts @@ -28,17 +28,17 @@ describe('cascader', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, ReactiveFormsModule, NoopAnimationsModule, NzCascaderModule ], - declarations: [ NzDemoCascaderDefaultComponent ], - providers : [] + imports: [FormsModule, ReactiveFormsModule, NoopAnimationsModule, NzCascaderModule], + declarations: [NzDemoCascaderDefaultComponent], + providers: [] }).compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -104,11 +104,13 @@ describe('cascader', () => { fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe(''); expect(testComponent.cascader.getSubmitValue().join(',')).toBe(''); - testComponent.values = [ 1, 2, 3 ]; + testComponent.values = [1, 2, 3]; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe('Zhejiang / Hangzhou / West Lake'); + expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe( + 'Zhejiang / Hangzhou / West Lake' + ); expect(testComponent.cascader.getSubmitValue().join(',')).toBe('1,2,3'); })); it('should no value and label property work', fakeAsync(() => { @@ -117,11 +119,13 @@ describe('cascader', () => { fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe(''); expect(testComponent.cascader.getSubmitValue().join(',')).toBe(''); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe('Zhejiang / Hangzhou / West Lake'); + expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe( + 'Zhejiang / Hangzhou / West Lake' + ); expect(testComponent.cascader.getSubmitValue().join(',')).toBe('zhejiang,hangzhou,xihu'); })); it('should showArrow work', () => { @@ -135,7 +139,7 @@ describe('cascader', () => { }); it('should allowClear work', () => { fixture.detectChanges(); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-picker-clear')).toBeDefined(); testComponent.nzAllowClear = false; @@ -185,61 +189,67 @@ describe('cascader', () => { expect(testComponent.onVisibleChange).toHaveBeenCalledTimes(1); const mouseleave = createMouseEvent('mouseleave'); - mouseleave.initMouseEvent('mouseleave', - false, /* canBubble */ - false, /* cancelable */ - window, /* view */ - 0, /* detail */ - 0, /* screenX */ - 0, /* screenY */ - 0, /* clientX */ - 0, /* clientY */ - false, /* ctrlKey */ - false, /* altKey */ - false, /* shiftKey */ - false, /* metaKey */ - 0, /* button */ - overlayContainerElement.querySelector('.ant-cascader-menu') /* relatedTarget */); + mouseleave.initMouseEvent( + 'mouseleave', + false /* canBubble */, + false /* cancelable */, + window /* view */, + 0 /* detail */, + 0 /* screenX */, + 0 /* screenY */, + 0 /* clientX */, + 0 /* clientY */, + false /* ctrlKey */, + false /* altKey */, + false /* shiftKey */, + false /* metaKey */, + 0 /* button */, + overlayContainerElement.querySelector('.ant-cascader-menu') /* relatedTarget */ + ); dispatchEvent(cascader.nativeElement, mouseleave); tick(300); fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - mouseleave.initMouseEvent('mouseleave', - false, /* canBubble */ - false, /* cancelable */ - window, /* view */ - 0, /* detail */ - 0, /* screenX */ - 0, /* screenY */ - 0, /* clientX */ - 0, /* clientY */ - false, /* ctrlKey */ - false, /* altKey */ - false, /* shiftKey */ - false, /* metaKey */ - 0, /* button */ - cascader.nativeElement /* relatedTarget */); + mouseleave.initMouseEvent( + 'mouseleave', + false /* canBubble */, + false /* cancelable */, + window /* view */, + 0 /* detail */, + 0 /* screenX */, + 0 /* screenY */, + 0 /* clientX */, + 0 /* clientY */, + false /* ctrlKey */, + false /* altKey */, + false /* shiftKey */, + false /* metaKey */, + 0 /* button */, + cascader.nativeElement /* relatedTarget */ + ); dispatchEvent(cascader.nativeElement, mouseleave); tick(300); fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - mouseleave.initMouseEvent('mouseleave', - false, /* canBubble */ - false, /* cancelable */ - window, /* view */ - 0, /* detail */ - 0, /* screenX */ - 0, /* screenY */ - 0, /* clientX */ - 0, /* clientY */ - false, /* ctrlKey */ - false, /* altKey */ - false, /* shiftKey */ - false, /* metaKey */ - 0, /* button */ - document.body /* relatedTarget */); + mouseleave.initMouseEvent( + 'mouseleave', + false /* canBubble */, + false /* cancelable */, + window /* view */, + 0 /* detail */, + 0 /* screenX */, + 0 /* screenY */, + 0 /* clientX */, + 0 /* clientY */, + false /* ctrlKey */, + false /* altKey */, + false /* shiftKey */, + false /* metaKey */, + 0 /* button */, + document.body /* relatedTarget */ + ); dispatchEvent(cascader.nativeElement, mouseleave); tick(300); fixture.detectChanges(); @@ -250,7 +260,7 @@ describe('cascader', () => { })); it('should mouse hover toggle open immediately', fakeAsync(() => { fixture.detectChanges(); - testComponent.nzTriggerAction = [ 'hover' ]; + testComponent.nzTriggerAction = ['hover']; testComponent.nzMouseEnterDelay = 0; testComponent.nzMouseLeaveDelay = 0; fixture.detectChanges(); @@ -271,7 +281,7 @@ describe('cascader', () => { it('should clear timer on option mouseenter and mouseleave', fakeAsync(() => { const mouseenter = createMouseEvent('mouseenter'); const mouseleave = createMouseEvent('mouseleave'); - const option = options1[ 0 ]; // zhejiang + const option = options1[0]; // zhejiang testComponent.nzExpandTrigger = 'hover'; fixture.detectChanges(); @@ -281,7 +291,9 @@ describe('cascader', () => { expect(testComponent.cascader.menuVisible).toBe(true); flush(); fixture.detectChanges(); - const optionEl = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const optionEl = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(optionEl.classList).not.toContain('ant-cascader-menu-item-active'); testComponent.cascader.onOptionMouseEnter(option, 0, mouseenter); @@ -364,7 +376,7 @@ describe('cascader', () => { expect(testComponent.onVisibleChange).toHaveBeenCalledTimes(1); })); it('should mouse leave not work when menu not open', fakeAsync(() => { - testComponent.nzTriggerAction = [ 'hover' ]; + testComponent.nzTriggerAction = ['hover']; fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(false); dispatchMouseEvent(cascader.nativeElement, 'mouseleave'); @@ -377,7 +389,7 @@ describe('cascader', () => { it('should clear value work', fakeAsync(() => { fixture.detectChanges(); testComponent.nzAllowClear = true; - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); expect(testComponent.values!.length).toBe(3); @@ -388,7 +400,7 @@ describe('cascader', () => { })); it('should clear value work 2', fakeAsync(() => { fixture.detectChanges(); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); expect(testComponent.values!.length).toBe(3); @@ -476,7 +488,7 @@ describe('cascader', () => { fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-input')).toBeNull(); testComponent.nzAllowClear = true; - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -495,29 +507,35 @@ describe('cascader', () => { it('should create label work', fakeAsync(() => { fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe(''); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe('Zhejiang / Hangzhou / West Lake'); + expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe( + 'Zhejiang / Hangzhou / West Lake' + ); })); it('should label template work', fakeAsync(() => { fixture.detectChanges(); expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText).toBe(''); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; testComponent.nzLabelRender = testComponent.renderTpl; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText.trim()).toBe('Zhejiang | Hangzhou | West Lake'); + expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText.trim()).toBe( + 'Zhejiang | Hangzhou | West Lake' + ); // fix clear testComponent.clearSelection(); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; testComponent.nzLabelRender = testComponent.renderTpl; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText.trim()).toBe('Zhejiang | Hangzhou | West Lake'); + expect(cascader.nativeElement.querySelector('.ant-cascader-picker-label').innerText.trim()).toBe( + 'Zhejiang | Hangzhou | West Lake' + ); })); it('should write value work', fakeAsync(() => { const control = testComponent.cascader; @@ -536,49 +554,53 @@ describe('cascader', () => { control.writeValue(''); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(1); - expect(control.getSubmitValue()[ 0 ]).toBe(''); - control.writeValue([ 'zhejiang' ]); + expect(control.getSubmitValue()[0]).toBe(''); + control.writeValue(['zhejiang']); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(1); - expect(control.getSubmitValue()[ 0 ]).toBe('zhejiang'); - control.writeValue([ 'zhejiang', 'hangzhou', 'xihu' ]); + expect(control.getSubmitValue()[0]).toBe('zhejiang'); + control.writeValue(['zhejiang', 'hangzhou', 'xihu']); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(3); const values = control.getSubmitValue(); - expect(values![ 0 ]).toBe('zhejiang'); - expect(values![ 1 ]).toBe('hangzhou'); - expect(values![ 2 ]).toBe('xihu'); + expect(values![0]).toBe('zhejiang'); + expect(values![1]).toBe('hangzhou'); + expect(values![2]).toBe('xihu'); control.writeValue([ - { value: 'zhejiang', text: 'Zj' }, { value: 'hangzhou', text: 'Hz' }, { value: 'xihu', text: 'Xh' } + { value: 'zhejiang', text: 'Zj' }, + { value: 'hangzhou', text: 'Hz' }, + { value: 'xihu', text: 'Xh' } ]); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(3); const values2 = control.getSubmitValue(); - expect(values2[ 0 ]).toBe('zhejiang'); - expect(values2[ 1 ]).toBe('hangzhou'); - expect(values2[ 2 ]).toBe('xihu'); + expect(values2[0]).toBe('zhejiang'); + expect(values2[1]).toBe('hangzhou'); + expect(values2[2]).toBe('xihu'); expect(control.labelRenderText).toBe('Zhejiang / Hangzhou / West Lake'); testComponent.nzOptions = []; // empty collection fixture.detectChanges(); - control.writeValue([ 'zhejiang', 'hangzhou', 'xihu' ]); // so these values are not match + control.writeValue(['zhejiang', 'hangzhou', 'xihu']); // so these values are not match fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(3); const values3 = control.getSubmitValue(); - expect(values3[ 0 ]).toBe('zhejiang'); - expect(values3[ 1 ]).toBe('hangzhou'); - expect(values3[ 2 ]).toBe('xihu'); + expect(values3[0]).toBe('zhejiang'); + expect(values3[1]).toBe('hangzhou'); + expect(values3[2]).toBe('xihu'); expect(control.labelRenderText).toBe('zhejiang / hangzhou / xihu'); control.writeValue([ - { value: 'zhejiang', label: 'ZJ' }, { value: 'hangzhou', label: 'HZ' }, { value: 'xihu', label: 'XH' } + { value: 'zhejiang', label: 'ZJ' }, + { value: 'hangzhou', label: 'HZ' }, + { value: 'xihu', label: 'XH' } ]); // so these values are not match fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(3); const values4 = control.getSubmitValue(); - expect(values4[ 0 ]).toBe('zhejiang'); - expect(values4[ 1 ]).toBe('hangzhou'); - expect(values4[ 2 ]).toBe('xihu'); + expect(values4[0]).toBe('zhejiang'); + expect(values4[1]).toBe('hangzhou'); + expect(values4[2]).toBe('xihu'); expect(control.labelRenderText).toBe('ZJ / HZ / XH'); })); it('should write value work on setting `nzOptions` asyn', fakeAsync(() => { @@ -598,23 +620,23 @@ describe('cascader', () => { control.writeValue(''); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(1); - expect(control.getSubmitValue()[ 0 ]).toBe(''); + expect(control.getSubmitValue()[0]).toBe(''); - control.writeValue([ 'zhejiang' ]); + control.writeValue(['zhejiang']); fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(1); - expect(control.getSubmitValue()[ 0 ]).toBe('zhejiang'); + expect(control.getSubmitValue()[0]).toBe('zhejiang'); expect(control.labelRenderText).toBe('zhejiang'); testComponent.nzOptions = options1; // update the nzOptions like asyn fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(1); - expect(control.getSubmitValue()[ 0 ]).toBe('zhejiang'); + expect(control.getSubmitValue()[0]).toBe('zhejiang'); expect(control.labelRenderText).toBe('Zhejiang'); })); it('should write value work on setting `nzOptions` asyn (match)', fakeAsync(() => { const control = testComponent.cascader; testComponent.nzOptions = null; - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); flush(); // force value to be write fixture.detectChanges(); @@ -623,26 +645,26 @@ describe('cascader', () => { testComponent.nzOptions = options1; // update the nzOptions like asyn fixture.detectChanges(); const values = control.getSubmitValue(); - expect(values![ 0 ]).toBe('zhejiang'); - expect(values![ 1 ]).toBe('hangzhou'); - expect(values![ 2 ]).toBe('xihu'); + expect(values![0]).toBe('zhejiang'); + expect(values![1]).toBe('hangzhou'); + expect(values![2]).toBe('xihu'); expect(control.labelRenderText).toBe('Zhejiang / Hangzhou / West Lake'); })); it('should write value work on setting `nzOptions` asyn (not match)', fakeAsync(() => { const control = testComponent.cascader; testComponent.nzOptions = null; - testComponent.values = [ 'zhejiang2', 'hangzhou2', 'xihu2' ]; + testComponent.values = ['zhejiang2', 'hangzhou2', 'xihu2']; fixture.detectChanges(); flush(); // force value to be write fixture.detectChanges(); expect(control.getSubmitValue().length).toBe(3); expect(control.labelRenderText).toBe('zhejiang2 / hangzhou2 / xihu2'); testComponent.nzOptions = options1; // update the nzOptions like asyn - fixture.detectChanges(); // but still the values is not match + fixture.detectChanges(); // but still the values is not match const values = control.getSubmitValue(); - expect(values![ 0 ]).toBe('zhejiang2'); - expect(values![ 1 ]).toBe('hangzhou2'); - expect(values![ 2 ]).toBe('xihu2'); + expect(values![0]).toBe('zhejiang2'); + expect(values![1]).toBe('hangzhou2'); + expect(values![2]).toBe('xihu2'); expect(control.labelRenderText).toBe('zhejiang2 / hangzhou2 / xihu2'); })); it('should click option to expand', () => { @@ -667,23 +689,29 @@ describe('cascader', () => { testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; itemEl1.click(); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; itemEl2.click(); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; itemEl3.click(); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 }); it('should click option to change column count 2', fakeAsync(() => { const LEFT_ARROW = 37; - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); cascader.nativeElement.click(); fixture.detectChanges(); @@ -692,9 +720,15 @@ describe('cascader', () => { expect(testComponent.cascader.menuVisible).toBe(true); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).toContain('ant-cascader-menu-item-active'); @@ -711,7 +745,9 @@ describe('cascader', () => { expect(itemEl3.classList).not.toContain('ant-cascader-menu-item-active'); expect(testComponent.values!.join(',')).toBe('zhejiang,hangzhou,xihu'); - const itemEl4 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; + const itemEl4 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; itemEl4.click(); // 选中一个叶子 fixture.detectChanges(); tick(300); @@ -727,18 +763,26 @@ describe('cascader', () => { testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; itemEl1.click(); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 - let itemEl21 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + let itemEl21 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(itemEl21.innerText.trim()).toBe('Hangzhou'); - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; itemEl2.click(); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 - itemEl21 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + itemEl21 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(itemEl21.innerText.trim()).toBe('Nanjing'); }); it('should click disabled option false to expand', fakeAsync(() => { @@ -746,8 +790,12 @@ describe('cascader', () => { fixture.detectChanges(); testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const optionEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 - const optionEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第1列第2个 + const optionEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 + const optionEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第1列第2个 expect(optionEl1.classList).not.toContain('ant-cascader-menu-item-active'); expect(optionEl2.classList).not.toContain('ant-cascader-menu-item-active'); @@ -765,13 +813,19 @@ describe('cascader', () => { testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - (overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement).click(); // 第1列第1个 + (overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement).click(); // 第1列第1个 fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - (overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement).click(); // 第2列第1个 + (overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement).click(); // 第2列第1个 fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - (overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement).click(); // 第3列第1个 + (overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement).click(); // 第3列第1个 fixture.detectChanges(); tick(200); fixture.detectChanges(); @@ -817,12 +871,16 @@ describe('cascader', () => { fixture.detectChanges(); testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:last-child') as HTMLElement; // 第1列最后1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:last-child' + ) as HTMLElement; // 第1列最后1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:first-child') as HTMLElement; // 第1列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:first-child' + ) as HTMLElement; // 第1列第1个 expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', UP_ARROW); fixture.detectChanges(); @@ -834,7 +892,9 @@ describe('cascader', () => { fixture.detectChanges(); testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', DOWN_ARROW); fixture.detectChanges(); @@ -850,32 +910,48 @@ describe('cascader', () => { fixture.detectChanges(); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); - let itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + let itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); - let itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + let itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', RIGHT_ARROW); fixture.detectChanges(); - itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); - itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl3.classList).toContain('ant-cascader-menu-item-active'); })); it('should navigate left when press LEFT_ARROW', fakeAsync(() => { const LEFT_ARROW = 37; fixture.detectChanges(); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); flush(); // wait for cdk-overlay to open fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).toContain('ant-cascader-menu-item-active'); @@ -926,9 +1002,9 @@ describe('cascader', () => { expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(3); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); - expect(testComponent.values![ 2 ]).toBe('xihu'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); + expect(testComponent.values![2]).toBe('xihu'); flush(); // wait for cdk-overlay to close fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(false); @@ -942,8 +1018,12 @@ describe('cascader', () => { fixture.detectChanges(); testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const optionEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 - const optionEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第1列第2个 + const optionEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 + const optionEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第1列第2个 expect(optionEl1.classList).not.toContain('ant-cascader-menu-item-active'); expect(optionEl2.classList).not.toContain('ant-cascader-menu-item-active'); @@ -957,10 +1037,18 @@ describe('cascader', () => { expect(optionEl1.classList).toContain('ant-cascader-menu-item-active'); expect(optionEl2.classList).not.toContain('ant-cascader-menu-item-active'); - const optionEl11 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 - const optionEl12 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第2列第1个 - const optionEl13 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(3)') as HTMLElement; // 第2列第1个 - const optionEl14 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(4)') as HTMLElement; // 第2列第1个 + const optionEl11 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 + const optionEl12 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第2列第1个 + const optionEl13 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(3)' + ) as HTMLElement; // 第2列第1个 + const optionEl14 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(4)' + ) as HTMLElement; // 第2列第1个 expect(optionEl11.classList).not.toContain('ant-cascader-menu-item-active'); expect(optionEl12.classList).not.toContain('ant-cascader-menu-item-active'); expect(optionEl13.classList).not.toContain('ant-cascader-menu-item-active'); @@ -1000,7 +1088,7 @@ describe('cascader', () => { const Z = 90; const ZERO = 48; const NINE = 57; - const keys = [ PAGE_UP, PAGE_DOWN, TAB, HOME, END, SPACE, COMMA, DELETE ]; + const keys = [PAGE_UP, PAGE_DOWN, TAB, HOME, END, SPACE, COMMA, DELETE]; for (let k = A; k <= Z; k++) { keys.push(k); } @@ -1027,7 +1115,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); dispatchMouseEvent(itemEl1, 'mouseenter'); @@ -1035,7 +1125,9 @@ describe('cascader', () => { tick(200); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); expect(testComponent.values).toBeNull(); // not select yet @@ -1052,7 +1144,9 @@ describe('cascader', () => { tick(200); fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).not.toContain('ant-cascader-menu-item-active'); @@ -1082,9 +1176,9 @@ describe('cascader', () => { fixture.detectChanges(); expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(3); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); - expect(testComponent.values![ 2 ]).toBe('xihu'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); + expect(testComponent.values![2]).toBe('xihu'); flush(); // wait for cdk-overlay to close fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(0); // 0列 @@ -1102,7 +1196,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第1列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第1列第1个 expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); dispatchMouseEvent(itemEl2, 'mouseenter'); @@ -1131,7 +1227,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); itemEl1.click(); fixture.detectChanges(); @@ -1141,9 +1239,11 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(1); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); + expect(testComponent.values![0]).toBe('zhejiang'); - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); itemEl2.click(); @@ -1155,10 +1255,12 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(2); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).not.toContain('ant-cascader-menu-item-active'); @@ -1169,9 +1271,9 @@ describe('cascader', () => { expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(3); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); - expect(testComponent.values![ 2 ]).toBe('xihu'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); + expect(testComponent.values![2]).toBe('xihu'); flush(); // wait for cdk-overlay to close fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(0); // 0列 @@ -1190,7 +1292,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); dispatchMouseEvent(itemEl1, 'mouseenter'); fixture.detectChanges(); @@ -1202,7 +1306,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 expect(testComponent.values).toBeNull(); // mouseenter does not trigger selection - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); dispatchMouseEvent(itemEl2, 'mouseenter'); @@ -1216,7 +1322,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 expect(testComponent.values).toBeNull(); // mouseenter does not trigger selection - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).not.toContain('ant-cascader-menu-item-active'); @@ -1234,9 +1342,9 @@ describe('cascader', () => { expect(testComponent.values).toBeDefined(); // click trigger selection expect(testComponent.values!.length).toBe(3); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); - expect(testComponent.values![ 2 ]).toBe('xihu'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); + expect(testComponent.values![2]).toBe('xihu'); flush(); // wait for cdk-overlay to close fixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(0); // 0列 @@ -1251,8 +1359,12 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - let itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 - let itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第1列第2个 + let itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 + let itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第1列第2个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); itemEl2.click(); @@ -1267,25 +1379,29 @@ describe('cascader', () => { fixture.detectChanges(); expect(testComponent.cascader.menuVisible).toBe(true); - itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 - itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; // 第1列第2个 + itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 + itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; // 第1列第2个 expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(1); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); + expect(testComponent.values![0]).toBe('zhejiang'); })); it('should position change correct', () => { const fakeTopEvent = { connectionPair: { - originX : 'center', - originY : 'top', + originX: 'center', + originY: 'top', overlayX: 'center', overlayY: 'bottom' } } as ConnectedOverlayPositionChange; const fakeBottomEvent = { connectionPair: { - originX : 'center', - originY : 'bottom', + originX: 'center', + originY: 'bottom', overlayX: 'center', overlayY: 'top' } @@ -1312,7 +1428,9 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText).toBe('Zhejiang / Hangzhou / West Lake'); itemEl1.click(); @@ -1333,7 +1451,9 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText).toBe('Zhejiang / Hangzhou / West Lake'); itemEl1.click(); @@ -1355,7 +1475,9 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText).toBe('Zhejiang / Hangzhou / West Lake'); itemEl1.click(); @@ -1370,8 +1492,8 @@ describe('cascader', () => { it('should support custom sorter', fakeAsync(() => { testComponent.nzShowSearch = { sorter(a: CascaderOption[], b: CascaderOption[], _inputValue: string): number { - const l1 = a[ 0 ].label; - const l2 = b[ 0 ].label; // all reversed, just to be sure it works + const l1 = a[0].label; + const l2 = b[0].label; // all reversed, just to be sure it works return ('' + l1).localeCompare(l2!); } } as NzShowSearchOptions; @@ -1379,7 +1501,9 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText).toBe('Jiangsu / Nanjing / Zhong Hua Men'); itemEl1.click(); @@ -1397,9 +1521,11 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(itemEl1.innerText).toBe('Zhejiang / Hangzhou / West Lake'); - expect(testComponent.cascader.columns[ 0 ][ 0 ].disabled).toBe(true); + expect(testComponent.cascader.columns[0][0].disabled).toBe(true); itemEl1.click(); tick(300); fixture.detectChanges(); @@ -1414,11 +1540,11 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - expect(testComponent.cascader.columns[ 0 ][ 0 ].disabled).toBe(true); - expect(testComponent.cascader.columns[ 0 ][ 1 ].disabled).toBe(undefined); - expect(testComponent.cascader.columns[ 0 ][ 2 ].disabled).toBe(true); + expect(testComponent.cascader.columns[0][0].disabled).toBe(true); + expect(testComponent.cascader.columns[0][1].disabled).toBe(undefined); + expect(testComponent.cascader.columns[0][2].disabled).toBe(true); }); - it('should support arrow in search mode', (done) => { + it('should support arrow in search mode', done => { const DOWN_ARROW = 40; const ENTER = 13; testComponent.nzOptions = options2; @@ -1426,8 +1552,12 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)') as HTMLElement; - const itemEl4 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(4)') as HTMLElement; + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(2)' + ) as HTMLElement; + const itemEl4 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(4)' + ) as HTMLElement; dispatchKeyboardEvent(cascader.nativeElement, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); @@ -1451,7 +1581,9 @@ describe('cascader', () => { testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', LEFT_ARROW); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; fixture.detectChanges(); expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); dispatchKeyboardEvent(cascader.nativeElement, 'keydown', RIGHT_ARROW); @@ -1470,7 +1602,9 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'Roo'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText.trim()).toBe('暂无数据'); flush(); @@ -1482,13 +1616,17 @@ describe('cascader', () => { testComponent.cascader.inputValue = 'o'; testComponent.cascader.setMenuVisible(true); fixture.detectChanges(); - let itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + let itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(testComponent.cascader.isSearching).toBe(true); expect(itemEl1.innerText).toBe('Zhejiang / Hangzhou / West Lake'); testComponent.nzOptions = options2; fixture.detectChanges(); expect(testComponent.cascader.isSearching).toBe(true); - itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; + itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; expect(itemEl1.innerText).toBe('Option1 / Option11'); }); }); @@ -1499,17 +1637,17 @@ describe('cascader', () => { let testComponent: NzDemoCascaderLoadDataComponent; beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, ReactiveFormsModule, NoopAnimationsModule, NzCascaderModule ], - declarations: [ NzDemoCascaderLoadDataComponent ], - providers : [] + imports: [FormsModule, ReactiveFormsModule, NoopAnimationsModule, NzCascaderModule], + declarations: [NzDemoCascaderLoadDataComponent], + providers: [] }).compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -1539,7 +1677,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(1); // 1列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 expect(itemEl1.classList).not.toContain('ant-cascader-menu-item-active'); itemEl1.click(); fixture.detectChanges(); @@ -1549,7 +1689,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(2); // 2列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).not.toContain('ant-cascader-menu-item-active'); itemEl2.click(); @@ -1560,7 +1702,9 @@ describe('cascader', () => { expect(overlayContainerElement.querySelectorAll('.ant-cascader-menu').length).toBe(3); // 3列 expect(testComponent.values).toBeNull(); // not select yet - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 expect(itemEl1.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl2.classList).toContain('ant-cascader-menu-item-active'); expect(itemEl3.classList).not.toContain('ant-cascader-menu-item-active'); @@ -1582,14 +1726,14 @@ describe('cascader', () => { expect(testComponent.addCallTimes).toHaveBeenCalledTimes(4); expect(testComponent.values).toBeDefined(); expect(testComponent.values!.length).toBe(3); - expect(testComponent.values![ 0 ]).toBe('zhejiang'); - expect(testComponent.values![ 1 ]).toBe('hangzhou'); - expect(testComponent.values![ 2 ]).toBe('xihu'); + expect(testComponent.values![0]).toBe('zhejiang'); + expect(testComponent.values![1]).toBe('hangzhou'); + expect(testComponent.values![2]).toBe('xihu'); })); it('should LOAD DATA work when specifies default value', fakeAsync(() => { spyOn(testComponent, 'addCallTimes'); - testComponent.values = [ 'zhejiang', 'hangzhou', 'xihu' ]; + testComponent.values = ['zhejiang', 'hangzhou', 'xihu']; fixture.detectChanges(); tick(3000); fixture.detectChanges(); @@ -1604,17 +1748,23 @@ describe('cascader', () => { fixture.detectChanges(); tick(1000); // wait for first row to load finish fixture.detectChanges(); - const itemEl1 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第1列第1个 + const itemEl1 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(1) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第1列第1个 itemEl1.click(); fixture.detectChanges(); tick(600); fixture.detectChanges(); - const itemEl2 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第2列第1个 + const itemEl2 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(2) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第2列第1个 itemEl2.click(); fixture.detectChanges(); tick(600); fixture.detectChanges(); - const itemEl3 = overlayContainerElement.querySelector('.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)') as HTMLElement; // 第3列第1个 + const itemEl3 = overlayContainerElement.querySelector( + '.ant-cascader-menu:nth-child(3) .ant-cascader-menu-item:nth-child(1)' + ) as HTMLElement; // 第3列第1个 itemEl3.click(); fixture.detectChanges(); tick(600); @@ -1632,163 +1782,216 @@ describe('cascader', () => { fixture.detectChanges(); expect(testComponent.values!.length).toBe(0); })); - }); }); -const ID_NAME_LIST = [ { - id : 1, - name : 'Zhejiang', - children: [ { - id : 2, - name : 'Hangzhou', - children: [ { - id : 3, - name : 'West Lake', - isLeaf: true - } ] - } ] -} ]; - -const options1 = [ { - value : 'zhejiang', - label : 'Zhejiang', - l : 'Zhejiang', - children: [ { - value : 'hangzhou', - label : 'Hangzhou', - l : 'Hangzhou', - children: [ { - value : 'xihu', - l : 'West Lake', - label : 'West Lake', - isLeaf: true - } ] - }, { - value : 'ningbo', - label : 'Ningbo', - l : 'Ningbo', - isLeaf: true - } ] -}, { - value : 'jiangsu', - label : 'Jiangsu', - l : 'Jiangsu', - children: [ { - value : 'nanjing', - label : 'Nanjing', - l : 'Nanjing', - children: [ { - value : 'zhonghuamen', - label : 'Zhong Hua Men', - l : 'Zhong Hua Men', - isLeaf: true - } ] - } ] -} ]; - -const options2 = [ { - value : 'option1', - label : 'Option1', - children: [ { - value : 'option11', - label : 'Option11', - disabled: true, - isLeaf : true - }, { - value : 'option12', - label : 'Option12', - isLeaf: true - }, { - value : 'option13', - label : 'Option13', +const ID_NAME_LIST = [ + { + id: 1, + name: 'Zhejiang', + children: [ + { + id: 2, + name: 'Hangzhou', + children: [ + { + id: 3, + name: 'West Lake', + isLeaf: true + } + ] + } + ] + } +]; + +const options1 = [ + { + value: 'zhejiang', + label: 'Zhejiang', + l: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + l: 'Hangzhou', + children: [ + { + value: 'xihu', + l: 'West Lake', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + l: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + l: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + l: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + l: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; + +const options2 = [ + { + value: 'option1', + label: 'Option1', + children: [ + { + value: 'option11', + label: 'Option11', + disabled: true, + isLeaf: true + }, + { + value: 'option12', + label: 'Option12', + isLeaf: true + }, + { + value: 'option13', + label: 'Option13', + disabled: true, + isLeaf: true + }, + { + value: 'option14', + label: 'Option14', + isLeaf: true + } + ] + }, + { + value: 'option2', + label: 'Option2', disabled: true, - isLeaf : true - }, { - value : 'option14', - label : 'Option14', - isLeaf: true - } ] -}, { - value : 'option2', - label : 'Option2', - disabled: true, - children: [ { - value : 'option21', - label : 'Option21', - isLeaf: true - }, { - value : 'option22', - label : 'Option22', - isLeaf: true - } ] -} ]; - -const options3 = [ { - value : 'zhejiang', - label : 'Zhejiang', - children: [ { - value : 'hangzhou', - label : 'Hangzhou', - children: [ { - value : 'xihu', - label : 'West Lake', - isLeaf: true - } ] - }, { - value : 'ningbo', - label : 'Ningbo', - isLeaf: true - } ] -}, { - value : 'jiangsu', - label : 'Jiangsu', - children: [ { - value : 'nanjing', - label : 'Nanjing', - children: [ { - value : 'zhonghuamen', - label : 'Zhong Hua Men', - isLeaf: true - } ] - }, { - value : 'suzhou', - label : 'Suzhou', - isLeaf: true - } ] -} ]; - -const options4 = [ { - value : 'zhejiang', - label : 'Zhejiang', - children: [ { - value : 'hangzhou', - label : 'Hangzhou', + children: [ + { + value: 'option21', + label: 'Option21', + isLeaf: true + }, + { + value: 'option22', + label: 'Option22', + isLeaf: true + } + ] + } +]; + +const options3 = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + }, + { + value: 'suzhou', + label: 'Suzhou', + isLeaf: true + } + ] + } +]; + +const options4 = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + disabled: true, + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', disabled: true, - children: [ { - value : 'xihu', - label : 'West Lake', - isLeaf: true - } ] - }, { - value : 'ningbo', - label : 'Ningbo', - isLeaf: true - } ] -}, { - value : 'jiangsu', - label : 'Jiangsu', - disabled: true, - children: [ { - value : 'nanjing', - label : 'Nanjing', - children: [ { - value : 'zhonghuamen', - label : 'Zhong Hua Men', - isLeaf: true - } ] - } ] -} ]; + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } +]; const options5: any[] = []; // tslint:disable-line:no-any @@ -1819,17 +2022,18 @@ const options5: any[] = []; // tslint:disable-line:no-any [nzChangeOn]="nzChangeOn" [nzChangeOnSelect]="nzChangeOnSelect" (ngModelChange)="onValueChanges($event)" - (nzVisibleChange)="onVisibleChange($event)"> + (nzVisibleChange)="onVisibleChange($event)" + > - {{label}}{{isLast ? '' : ' | '}} + {{ label }}{{ isLast ? '' : ' | ' }} `, - styles : [ - ` + styles: [ + ` .ant-cascader-picker { width: 300px; } @@ -1869,7 +2073,7 @@ export class NzDemoCascaderDefaultComponent { fakeChangeOn = (node: any, _index: number): boolean => { return node.value === 'zhejiang'; - } + }; clearSelection(): void { this.cascader.clearSelection(); @@ -1884,11 +2088,12 @@ export class NzDemoCascaderDefaultComponent { [(ngModel)]="values" [nzLoadData]="nzLoadData" (ngModelChange)="onValueChanges($event)" - (nzVisibleChange)="onVisibleChange($event)"> + (nzVisibleChange)="onVisibleChange($event)" + > `, - styles : [ - ` + styles: [ + ` .ant-cascader-picker { width: 300px; } @@ -1905,35 +2110,40 @@ export class NzDemoCascaderLoadDataComponent { this.addCallTimes(); return new Promise((resolve, reject) => { setTimeout(() => { - if (index < 0) { // if index less than 0 it is root node - node.children = [ { - value: 'zhejiang', - label: 'Zhejiang' - } ]; + if (index < 0) { + // if index less than 0 it is root node + node.children = [ + { + value: 'zhejiang', + label: 'Zhejiang' + } + ]; resolve(); } else if (index === 0) { - node.children = [ { - value: 'hangzhou', - label: 'Hangzhou' - } ]; + node.children = [ + { + value: 'hangzhou', + label: 'Hangzhou' + } + ]; resolve(); } else if (index === 1) { - node.children = [ { - value: 'xihu', - label: 'West Lake' - } ]; + node.children = [ + { + value: 'xihu', + label: 'West Lake' + } + ]; resolve(); } else { reject(); } }, 500); }); - } + }; - public addCallTimes(): void { - } + public addCallTimes(): void {} onVisibleChange = jasmine.createSpy('open change'); onValueChanges = jasmine.createSpy('value change'); - } diff --git a/components/cascader/types.ts b/components/cascader/types.ts index 53186b843d7..51ee4a620ec 100644 --- a/components/cascader/types.ts +++ b/components/cascader/types.ts @@ -2,7 +2,7 @@ export type NzCascaderExpandTrigger = 'click' | 'hover'; export type NzCascaderTriggerType = 'click' | 'hover'; -export type NzCascaderSize = 'small' | 'large' | 'default' ; +export type NzCascaderSize = 'small' | 'large' | 'default'; export interface CascaderOption { value?: any; // tslint:disable-line:no-any @@ -14,7 +14,7 @@ export interface CascaderOption { parent?: CascaderOption; children?: CascaderOption[]; - [ key: string ]: any; // tslint:disable-line:no-any + [key: string]: any; // tslint:disable-line:no-any } export interface CascaderSearchOption extends CascaderOption { diff --git a/components/checkbox/demo/basic.ts b/components/checkbox/demo/basic.ts index f46d14c83af..d02fe80638d 100644 --- a/components/checkbox/demo/basic.ts +++ b/components/checkbox/demo/basic.ts @@ -2,7 +2,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-checkbox-basic', - template: `` + template: ` + + ` }) export class NzDemoCheckboxBasicComponent { checked = true; diff --git a/components/checkbox/demo/check-all.ts b/components/checkbox/demo/check-all.ts index e59f37be73b..7e6c91efbcd 100644 --- a/components/checkbox/demo/check-all.ts +++ b/components/checkbox/demo/check-all.ts @@ -4,11 +4,16 @@ import { Component } from '@angular/core'; selector: 'nz-demo-checkbox-check-all', template: `
-
-
+
` }) diff --git a/components/checkbox/demo/controller.ts b/components/checkbox/demo/controller.ts index a38b9627f32..1bbca41d98b 100644 --- a/components/checkbox/demo/controller.ts +++ b/components/checkbox/demo/controller.ts @@ -17,10 +17,12 @@ import { Component } from '@angular/core';

`, - styles : [ - `button { - margin-right: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + } + ` ] }) export class NzDemoCheckboxControllerComponent { diff --git a/components/checkbox/demo/disabled.ts b/components/checkbox/demo/disabled.ts index e5df5c550d4..099096bcdb9 100644 --- a/components/checkbox/demo/disabled.ts +++ b/components/checkbox/demo/disabled.ts @@ -4,8 +4,8 @@ import { Component } from '@angular/core'; selector: 'nz-demo-checkbox-disabled', template: ` -
- ` +
+ + ` }) -export class NzDemoCheckboxDisabledComponent { -} +export class NzDemoCheckboxDisabledComponent {} diff --git a/components/checkbox/demo/group.ts b/components/checkbox/demo/group.ts index e141729634a..0579d3eb483 100644 --- a/components/checkbox/demo/group.ts +++ b/components/checkbox/demo/group.ts @@ -4,11 +4,11 @@ import { Component } from '@angular/core'; selector: 'nz-demo-checkbox-group', template: ` -
-
+
+
-
-
+
+
` }) diff --git a/components/checkbox/demo/layout.ts b/components/checkbox/demo/layout.ts index 705bb1dd8c3..25938505d29 100644 --- a/components/checkbox/demo/layout.ts +++ b/components/checkbox/demo/layout.ts @@ -15,7 +15,6 @@ import { Component } from '@angular/core'; ` }) export class NzDemoCheckboxLayoutComponent { - log(value: string[]): void { console.log(value); } diff --git a/components/checkbox/nz-checkbox-group.component.ts b/components/checkbox/nz-checkbox-group.component.ts index ef5afa1da23..64d85184feb 100644 --- a/components/checkbox/nz-checkbox-group.component.ts +++ b/components/checkbox/nz-checkbox-group.component.ts @@ -20,15 +20,15 @@ export interface NzCheckBoxOptionInterface { } @Component({ - selector : 'nz-checkbox-group', + selector: 'nz-checkbox-group', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-checkbox-group.component.html', - providers : [ + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-checkbox-group.component.html', + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzCheckboxGroupComponent), - multi : true + multi: true } ] }) @@ -48,7 +48,12 @@ export class NzCheckboxGroupComponent implements ControlValueAccessor, OnInit { return option.value; } - constructor(private elementRef: ElementRef, private focusMonitor: FocusMonitor, private cdr: ChangeDetectorRef, renderer: Renderer2) { + constructor( + private elementRef: ElementRef, + private focusMonitor: FocusMonitor, + private cdr: ChangeDetectorRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-checkbox-group'); } diff --git a/components/checkbox/nz-checkbox-wrapper.component.ts b/components/checkbox/nz-checkbox-wrapper.component.ts index e6743fe9a43..050135359d8 100644 --- a/components/checkbox/nz-checkbox-wrapper.component.ts +++ b/components/checkbox/nz-checkbox-wrapper.component.ts @@ -11,11 +11,11 @@ import { import { NzCheckboxComponent } from './nz-checkbox.component'; @Component({ - selector : 'nz-checkbox-wrapper', + selector: 'nz-checkbox-wrapper', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-checkbox-wrapper.component.html' + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-checkbox-wrapper.component.html' }) export class NzCheckboxWrapperComponent { @Output() readonly nzOnChange = new EventEmitter(); diff --git a/components/checkbox/nz-checkbox.component.ts b/components/checkbox/nz-checkbox.component.ts index 204fe834ff1..0302f8b8479 100644 --- a/components/checkbox/nz-checkbox.component.ts +++ b/components/checkbox/nz-checkbox.component.ts @@ -24,19 +24,19 @@ import { InputBoolean } from '../core/util/convert'; import { NzCheckboxWrapperComponent } from './nz-checkbox-wrapper.component'; @Component({ - selector : '[nz-checkbox]', + selector: '[nz-checkbox]', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-checkbox.component.html', - providers : [ + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-checkbox.component.html', + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzCheckboxComponent), - multi : true + multi: true } ], - host : { + host: { '(click)': 'hostClick($event)' } }) @@ -113,7 +113,13 @@ export class NzCheckboxComponent implements OnInit, ControlValueAccessor, OnChan } } - constructor(private elementRef: ElementRef, private renderer: Renderer2, @Optional() private nzCheckboxWrapperComponent: NzCheckboxWrapperComponent, private cdr: ChangeDetectorRef, private focusMonitor: FocusMonitor) { + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + @Optional() private nzCheckboxWrapperComponent: NzCheckboxWrapperComponent, + private cdr: ChangeDetectorRef, + private focusMonitor: FocusMonitor + ) { renderer.addClass(elementRef.nativeElement, 'ant-checkbox-wrapper'); } diff --git a/components/checkbox/nz-checkbox.module.ts b/components/checkbox/nz-checkbox.module.ts index c99426e4b7b..4a195a414df 100644 --- a/components/checkbox/nz-checkbox.module.ts +++ b/components/checkbox/nz-checkbox.module.ts @@ -8,17 +8,8 @@ import { NzCheckboxWrapperComponent } from './nz-checkbox-wrapper.component'; import { NzCheckboxComponent } from './nz-checkbox.component'; @NgModule({ - imports : [ CommonModule, FormsModule, ObserversModule ], - declarations: [ - NzCheckboxComponent, - NzCheckboxGroupComponent, - NzCheckboxWrapperComponent - ], - exports : [ - NzCheckboxComponent, - NzCheckboxGroupComponent, - NzCheckboxWrapperComponent - ] + imports: [CommonModule, FormsModule, ObserversModule], + declarations: [NzCheckboxComponent, NzCheckboxGroupComponent, NzCheckboxWrapperComponent], + exports: [NzCheckboxComponent, NzCheckboxGroupComponent, NzCheckboxWrapperComponent] }) -export class NzCheckboxModule { -} +export class NzCheckboxModule {} diff --git a/components/checkbox/nz-checkbox.spec.ts b/components/checkbox/nz-checkbox.spec.ts index 85bf769b64a..1ca479c1b3a 100644 --- a/components/checkbox/nz-checkbox.spec.ts +++ b/components/checkbox/nz-checkbox.spec.ts @@ -11,8 +11,14 @@ import { NzCheckboxModule } from './nz-checkbox.module'; describe('checkbox', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzCheckboxModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestCheckboxSingleComponent, NzTestCheckboxGroupComponent, NzTestCheckboxFormComponent, NzTestCheckboxGroupFormComponent, NzTestCheckboxWrapperComponent ] + imports: [NzCheckboxModule, FormsModule, ReactiveFormsModule], + declarations: [ + NzTestCheckboxSingleComponent, + NzTestCheckboxGroupComponent, + NzTestCheckboxFormComponent, + NzTestCheckboxGroupFormComponent, + NzTestCheckboxWrapperComponent + ] }); TestBed.compileComponents(); })); @@ -32,8 +38,12 @@ describe('checkbox', () => { fixture.detectChanges(); expect(checkbox.nativeElement.classList.contains('ant-checkbox-wrapper')).toBe(true); expect(checkbox.nativeElement.firstElementChild!.classList.contains('ant-checkbox')).toBe(true); - expect(checkbox.nativeElement.firstElementChild.firstElementChild!.classList.contains('ant-checkbox-input')).toBe(true); - expect(checkbox.nativeElement.firstElementChild.lastElementChild.classList.contains('ant-checkbox-inner')).toBe(true); + expect(checkbox.nativeElement.firstElementChild.firstElementChild!.classList.contains('ant-checkbox-input')).toBe( + true + ); + expect(checkbox.nativeElement.firstElementChild.lastElementChild.classList.contains('ant-checkbox-inner')).toBe( + true + ); expect(checkbox.nativeElement.lastElementChild.innerText).toBe('Checkbox'); }); it('should click change', () => { @@ -132,43 +142,43 @@ describe('checkbox', () => { flush(); fixture.detectChanges(); expect(checkboxGroup.nativeElement.classList).toContain('ant-checkbox-group'); - expect(checkboxs[ 0 ].firstElementChild!.classList).toContain('ant-checkbox-checked'); - expect(checkboxs[ 1 ].firstElementChild!.classList).toContain('ant-checkbox-disabled'); - expect(checkboxs[ 1 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); - expect(checkboxs[ 2 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[0].firstElementChild!.classList).toContain('ant-checkbox-checked'); + expect(checkboxs[1].firstElementChild!.classList).toContain('ant-checkbox-disabled'); + expect(checkboxs[1].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[2].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); })); it('should click correct', () => { fixture.detectChanges(); fixture.detectChanges(); - checkboxs[ 0 ].click(); + checkboxs[0].click(); fixture.detectChanges(); expect(testComponent.modelChange).toHaveBeenCalledTimes(1); - expect(checkboxs[ 0 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[0].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); }); it('should sub disabled work', () => { fixture.detectChanges(); fixture.detectChanges(); - checkboxs[ 1 ].click(); + checkboxs[1].click(); fixture.detectChanges(); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); - expect(checkboxs[ 1 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[1].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); }); it('should all disabled work', () => { testComponent.disabled = true; fixture.detectChanges(); fixture.detectChanges(); - checkboxs[ 2 ].click(); + checkboxs[2].click(); fixture.detectChanges(); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); - expect(checkboxs[ 2 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[2].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); }); it('should ngModel work', fakeAsync(() => { fixture.detectChanges(); - testComponent.options[ 0 ].checked = false; + testComponent.options[0].checked = false; fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(checkboxs[ 0 ].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(checkboxs[0].firstElementChild!.classList).not.toContain('ant-checkbox-checked'); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); })); }); @@ -230,20 +240,24 @@ describe('checkbox', () => { })); it('should set disabled work', fakeAsync(() => { flush(); - expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe(JSON.stringify([ - { label: 'Apple', value: 'Apple', checked: true }, - { label: 'Pear', value: 'Pear', disabled: true }, - { label: 'Orange', value: 'Orange' } - ])); + expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe( + JSON.stringify([ + { label: 'Apple', value: 'Apple', checked: true }, + { label: 'Pear', value: 'Pear', disabled: true }, + { label: 'Orange', value: 'Orange' } + ]) + ); inputElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe(JSON.stringify([ - { label: 'Apple', value: 'Apple', checked: false }, - { label: 'Pear', value: 'Pear', disabled: true }, - { label: 'Orange', value: 'Orange' } - ])); + expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe( + JSON.stringify([ + { label: 'Apple', value: 'Apple', checked: false }, + { label: 'Pear', value: 'Pear', disabled: true }, + { label: 'Orange', value: 'Orange' } + ]) + ); testComponent.disable(); fixture.detectChanges(); flush(); @@ -251,11 +265,13 @@ describe('checkbox', () => { inputElement.click(); flush(); fixture.detectChanges(); - expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe(JSON.stringify([ - { label: 'Apple', value: 'Apple', checked: false }, - { label: 'Pear', value: 'Pear', disabled: true }, - { label: 'Orange', value: 'Orange' } - ])); + expect(JSON.stringify(testComponent.formGroup.get('checkboxGroup')!.value)).toBe( + JSON.stringify([ + { label: 'Apple', value: 'Apple', checked: false }, + { label: 'Pear', value: 'Pear', disabled: true }, + { label: 'Orange', value: 'Orange' } + ]) + ); })); }); describe('checkbox wrapper', () => { @@ -289,8 +305,16 @@ describe('checkbox', () => { @Component({ selector: 'nz-test-checkbox-single', template: ` - ` + + ` }) export class NzTestCheckboxSingleComponent { @ViewChild(NzCheckboxComponent) nzCheckboxComponent: NzCheckboxComponent; @@ -304,8 +328,11 @@ export class NzTestCheckboxSingleComponent { @Component({ selector: 'nz-test-checkbox-group', template: ` - + ` }) export class NzTestCheckboxGroupComponent { @@ -347,7 +374,7 @@ export class NzTestCheckboxFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - checkbox: [ false ] + checkbox: [false] }); } @@ -369,11 +396,13 @@ export class NzTestCheckboxGroupFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - checkboxGroup: [ [ - { label: 'Apple', value: 'Apple', checked: true }, - { label: 'Pear', value: 'Pear', disabled: true }, - { label: 'Orange', value: 'Orange' } - ] ] + checkboxGroup: [ + [ + { label: 'Apple', value: 'Apple', checked: true }, + { label: 'Pear', value: 'Pear', disabled: true }, + { label: 'Orange', value: 'Orange' } + ] + ] }); } diff --git a/components/collapse/demo/accordion.ts b/components/collapse/demo/accordion.ts index 4671fef5876..5689dd99cc6 100644 --- a/components/collapse/demo/accordion.ts +++ b/components/collapse/demo/accordion.ts @@ -5,31 +5,31 @@ import { Component } from '@angular/core'; template: ` -

{{panel.name}} content

+

{{ panel.name }} content

`, - styles : [] + styles: [] }) export class NzDemoCollapseAccordionComponent { panels = [ { - active : true, - name : 'This is panel header 1', + active: true, + name: 'This is panel header 1', childPanel: [ { active: false, - name : 'This is panel header 1-1' + name: 'This is panel header 1-1' } ] }, { active: false, - name : 'This is panel header 2' + name: 'This is panel header 2' }, { active: false, - name : 'This is panel header 3' + name: 'This is panel header 3' } ]; } diff --git a/components/collapse/demo/basic.ts b/components/collapse/demo/basic.ts index 14d32901851..090a1a9c3cf 100644 --- a/components/collapse/demo/basic.ts +++ b/components/collapse/demo/basic.ts @@ -4,29 +4,37 @@ import { Component } from '@angular/core'; selector: 'nz-demo-collapse-basic', template: ` - -

A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world.

+ +

+ A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome + guest in many households across the world. +

`, - styles : [] + styles: [] }) export class NzDemoCollapseBasicComponent { panels = [ { - active : true, - name : 'This is panel header 1', - disabled : false + active: true, + name: 'This is panel header 1', + disabled: false }, { - active : false, + active: false, disabled: false, - name : 'This is panel header 2' + name: 'This is panel header 2' }, { - active : false, + active: false, disabled: true, - name : 'This is panel header 3' + name: 'This is panel header 3' } ]; } diff --git a/components/collapse/demo/borderless.ts b/components/collapse/demo/borderless.ts index 0d9e076cddf..bc223becfe7 100644 --- a/components/collapse/demo/borderless.ts +++ b/components/collapse/demo/borderless.ts @@ -5,35 +5,35 @@ import { Component } from '@angular/core'; template: ` -

{{panel.name}} content

+

{{ panel.name }} content

`, - styles : [] + styles: [] }) export class NzDemoCollapseBorderlessComponent { panels = [ { - active : true, - disabled : false, - name : 'This is panel header 1', + active: true, + disabled: false, + name: 'This is panel header 1', childPannel: [ { - active : false, + active: false, disabled: true, - name : 'This is panel header 1-1' + name: 'This is panel header 1-1' } ] }, { - active : false, + active: false, disabled: true, - name : 'This is panel header 2' + name: 'This is panel header 2' }, { - active : false, + active: false, disabled: false, - name : 'This is panel header 3' + name: 'This is panel header 3' } ]; } diff --git a/components/collapse/demo/custom.ts b/components/collapse/demo/custom.ts index 0a1bf19f60d..bddd3df7187 100644 --- a/components/collapse/demo/custom.ts +++ b/components/collapse/demo/custom.ts @@ -4,9 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-collapse-custom', template: ` - -

{{panel.name}} content

+ +

{{ panel.name }} content

{{ active }} @@ -14,42 +20,42 @@ import { Component } from '@angular/core';
`, - styles : [] + styles: [] }) export class NzDemoCollapseCustomComponent { panels = [ { - active : true, - disabled : false, - name : 'This is panel header 1', + active: true, + disabled: false, + name: 'This is panel header 1', customStyle: { - 'background' : '#f7f7f7', + background: '#f7f7f7', 'border-radius': '4px', 'margin-bottom': '24px', - 'border' : '0px' + border: '0px' } }, { - active : false, - disabled : true, - name : 'This is panel header 2', - icon : 'double-right', + active: false, + disabled: true, + name: 'This is panel header 2', + icon: 'double-right', customStyle: { - 'background' : '#f7f7f7', + background: '#f7f7f7', 'border-radius': '4px', 'margin-bottom': '24px', - 'border' : '0px' + border: '0px' } }, { - active : false, - disabled : false, - name : 'This is panel header 3', + active: false, + disabled: false, + name: 'This is panel header 3', customStyle: { - 'background' : '#f7f7f7', + background: '#f7f7f7', 'border-radius': '4px', 'margin-bottom': '24px', - 'border' : '0px' + border: '0px' } } ]; diff --git a/components/collapse/demo/mix.ts b/components/collapse/demo/mix.ts index 97e5c22b9ee..f90f7d64878 100644 --- a/components/collapse/demo/mix.ts +++ b/components/collapse/demo/mix.ts @@ -5,46 +5,52 @@ import { Component } from '@angular/core'; template: ` -

{{panel.name}}

-
+

{{ panel.name }}

+
- -

A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world.

+ +

+ A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a + welcome guest in many households across the world. +

`, - styles : [] + styles: [] }) export class NzDemoCollapseMixComponent { panels = [ { - active : true, - disabled : false, - name : 'This is panel header 1', + active: true, + disabled: false, + name: 'This is panel header 1', childPanel: [ { active: true, - name : 'This is panel header 1-1' + name: 'This is panel header 1-1' }, { active: false, - name : 'This is panel header 1-2' + name: 'This is panel header 1-2' } ] }, { - active : false, + active: false, disabled: true, - name : 'This is panel header 2' + name: 'This is panel header 2' }, { - active : false, + active: false, disabled: false, - name : 'This is panel header 3' + name: 'This is panel header 3' } ]; } diff --git a/components/collapse/demo/noarrow.ts b/components/collapse/demo/noarrow.ts index c6407dcbe00..d9c9befc2c9 100644 --- a/components/collapse/demo/noarrow.ts +++ b/components/collapse/demo/noarrow.ts @@ -4,24 +4,33 @@ import { Component } from '@angular/core'; selector: 'nz-demo-collapse-noarrow', template: ` - -

A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome guest in many households across the world.

+ +

+ A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found as a welcome + guest in many households across the world. +

`, - styles : [] + styles: [] }) export class NzDemoCollapseNoarrowComponent { panels = [ { active: true, - name : 'This is panel header 1', - arrow : true + name: 'This is panel header 1', + arrow: true }, { active: false, - arrow : false, - name : 'This is panel header 2' + arrow: false, + name: 'This is panel header 2' } ]; } diff --git a/components/collapse/nz-collapse-panel.component.ts b/components/collapse/nz-collapse-panel.component.ts index c6d637932af..b18d9bc0de8 100644 --- a/components/collapse/nz-collapse-panel.component.ts +++ b/components/collapse/nz-collapse-panel.component.ts @@ -1,11 +1,16 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, - EventEmitter, Host, + Component, + ElementRef, + EventEmitter, + Host, HostBinding, - Input, OnDestroy, OnInit, - Output, Renderer2, + Input, + OnDestroy, + OnInit, + Output, + Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -15,21 +20,22 @@ import { InputBoolean } from '../core/util/convert'; import { NzCollapseComponent } from './nz-collapse.component'; @Component({ - selector : 'nz-collapse-panel', - templateUrl : './nz-collapse-panel.component.html', + selector: 'nz-collapse-panel', + templateUrl: './nz-collapse-panel.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - animations : [ collapseMotion ], - styles : [ - ` nz-collapse-panel { - display: block - }` + encapsulation: ViewEncapsulation.None, + animations: [collapseMotion], + styles: [ + ` + nz-collapse-panel { + display: block; + } + ` ], - host : { + host: { '[class.ant-collapse-no-arrow]': '!nzShowArrow' } }) - export class NzCollapsePanelComponent implements OnInit, OnDestroy { @Input() @InputBoolean() @HostBinding('class.ant-collapse-item-active') nzActive = false; @Input() @InputBoolean() @HostBinding('class.ant-collapse-item-disabled') nzDisabled = false; @@ -48,7 +54,12 @@ export class NzCollapsePanelComponent implements OnInit, OnDestroy { this.cdr.markForCheck(); } - constructor(private cdr: ChangeDetectorRef, @Host() private nzCollapseComponent: NzCollapseComponent, elementRef: ElementRef, renderer: Renderer2) { + constructor( + private cdr: ChangeDetectorRef, + @Host() private nzCollapseComponent: NzCollapseComponent, + elementRef: ElementRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-collapse-item'); } diff --git a/components/collapse/nz-collapse.component.ts b/components/collapse/nz-collapse.component.ts index f3ceb74659a..d032c14217a 100644 --- a/components/collapse/nz-collapse.component.ts +++ b/components/collapse/nz-collapse.component.ts @@ -1,21 +1,18 @@ -import { - ChangeDetectionStrategy, - Component, - Input, - ViewEncapsulation -} from '@angular/core'; +import { ChangeDetectionStrategy, Component, Input, ViewEncapsulation } from '@angular/core'; import { InputBoolean } from '../core/util/convert'; import { NzCollapsePanelComponent } from './nz-collapse-panel.component'; @Component({ - selector : 'nz-collapse', - templateUrl : './nz-collapse.component.html', + selector: 'nz-collapse', + templateUrl: './nz-collapse.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - styles : [ - `nz-collapse { - display: block; - }` + encapsulation: ViewEncapsulation.None, + styles: [ + ` + nz-collapse { + display: block; + } + ` ] }) export class NzCollapseComponent { @@ -33,13 +30,15 @@ export class NzCollapseComponent { click(collapse: NzCollapsePanelComponent): void { if (this.nzAccordion && !collapse.nzActive) { - this.listOfNzCollapsePanelComponent.filter(item => item !== collapse).forEach(item => { - if (item.nzActive) { - item.nzActive = false; - item.nzActiveChange.emit(item.nzActive); - item.markForCheck(); - } - }); + this.listOfNzCollapsePanelComponent + .filter(item => item !== collapse) + .forEach(item => { + if (item.nzActive) { + item.nzActive = false; + item.nzActiveChange.emit(item.nzActive); + item.markForCheck(); + } + }); } collapse.nzActive = !collapse.nzActive; collapse.nzActiveChange.emit(collapse.nzActive); diff --git a/components/collapse/nz-collapse.module.ts b/components/collapse/nz-collapse.module.ts index e96dc685171..2363082bbfc 100644 --- a/components/collapse/nz-collapse.module.ts +++ b/components/collapse/nz-collapse.module.ts @@ -7,10 +7,8 @@ import { NzCollapsePanelComponent } from './nz-collapse-panel.component'; import { NzCollapseComponent } from './nz-collapse.component'; @NgModule({ - declarations: [ NzCollapsePanelComponent, NzCollapseComponent ], - exports : [ NzCollapsePanelComponent, NzCollapseComponent ], - imports : [ CommonModule, NzIconModule, NzAddOnModule ] + declarations: [NzCollapsePanelComponent, NzCollapseComponent], + exports: [NzCollapsePanelComponent, NzCollapseComponent], + imports: [CommonModule, NzIconModule, NzAddOnModule] }) - -export class NzCollapseModule { -} +export class NzCollapseModule {} diff --git a/components/collapse/nz-collapse.spec.ts b/components/collapse/nz-collapse.spec.ts index 96a075962be..52347a795c5 100644 --- a/components/collapse/nz-collapse.spec.ts +++ b/components/collapse/nz-collapse.spec.ts @@ -10,8 +10,8 @@ import { NzCollapseModule } from './nz-collapse.module'; describe('collapse', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzCollapseModule, NoopAnimationsModule ], - declarations: [ NzTestCollapseBasicComponent, NzTestCollapseTemplateComponent, NzTestCollapseIconComponent ] + imports: [NzCollapseModule, NoopAnimationsModule], + declarations: [NzTestCollapseBasicComponent, NzTestCollapseTemplateComponent, NzTestCollapseIconComponent] }); TestBed.compileComponents(); })); @@ -42,92 +42,92 @@ describe('collapse', () => { }); it('should showArrow work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.querySelector('.ant-collapse-arrow').firstElementChild).toBeDefined(); + expect(panels[0].nativeElement.querySelector('.ant-collapse-arrow').firstElementChild).toBeDefined(); testComponent.showArrow = false; fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.querySelector('.ant-collapse-arrow')).toBeNull(); + expect(panels[0].nativeElement.querySelector('.ant-collapse-arrow')).toBeNull(); }); it('should active work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); testComponent.active01 = true; fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.classList).toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(0); }); it('should click work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01).toBe(false); - panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[0].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active01).toBe(true); - expect(panels[ 0 ].nativeElement.classList).toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(1); }); it('should disabled work', () => { testComponent.disabled = true; fixture.detectChanges(); - expect(panels[ 1 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active02).toBe(false); - panels[ 1 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[1].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active02).toBe(false); - expect(panels[ 1 ].nativeElement.classList).toContain('ant-collapse-item-disabled'); - expect(panels[ 1 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).toContain('ant-collapse-item-disabled'); + expect(panels[1].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active02Change).toHaveBeenCalledTimes(0); }); it('should accordion work', () => { testComponent.accordion = true; fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01).toBe(false); - panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[0].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active01).toBe(true); expect(testComponent.active02).toBe(false); - expect(panels[ 0 ].nativeElement.classList).toContain('ant-collapse-item-active'); - expect(panels[ 1 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(1); expect(testComponent.active02Change).toHaveBeenCalledTimes(0); - panels[ 1 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[1].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active01).toBe(false); expect(testComponent.active02).toBe(true); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); - expect(panels[ 1 ].nativeElement.classList).toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(2); expect(testComponent.active02Change).toHaveBeenCalledTimes(1); }); it('should click to fold up work with accordion', () => { testComponent.accordion = true; fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01).toBe(false); - panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[0].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); - panels[ 1 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[1].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); - panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[0].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active01).toBe(true); expect(testComponent.active02).toBe(false); - expect(panels[ 0 ].nativeElement.classList).toContain('ant-collapse-item-active'); - expect(panels[ 1 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(3); expect(testComponent.active02Change).toHaveBeenCalledTimes(2); - panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').click(); + panels[0].nativeElement.querySelector('.ant-collapse-header').click(); fixture.detectChanges(); expect(testComponent.active01).toBe(false); expect(testComponent.active02).toBe(false); - expect(panels[ 0 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); - expect(panels[ 1 ].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[0].nativeElement.classList).not.toContain('ant-collapse-item-active'); + expect(panels[1].nativeElement.classList).not.toContain('ant-collapse-item-active'); expect(testComponent.active01Change).toHaveBeenCalledTimes(4); expect(testComponent.active02Change).toHaveBeenCalledTimes(2); }); it('should header work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').innerText).toBe('string'); + expect(panels[0].nativeElement.querySelector('.ant-collapse-header').innerText).toBe('string'); }); }); describe('collapse template', () => { @@ -140,7 +140,7 @@ describe('collapse', () => { }); it('should header work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.querySelector('.ant-collapse-header').innerText).toBe('template'); + expect(panels[0].nativeElement.querySelector('.ant-collapse-header').innerText).toBe('template'); }); }); @@ -154,9 +154,9 @@ describe('collapse', () => { }); it('should icon work', () => { fixture.detectChanges(); - expect(panels[ 0 ].nativeElement.querySelector('.anticon-right')).toBeDefined(); - expect(panels[ 1 ].nativeElement.querySelector('.anticon-double-right')).toBeDefined(); - expect(panels[ 2 ].nativeElement.querySelector('.anticon-caret-right')).toBeDefined(); + expect(panels[0].nativeElement.querySelector('.anticon-right')).toBeDefined(); + expect(panels[1].nativeElement.querySelector('.anticon-double-right')).toBeDefined(); + expect(panels[2].nativeElement.querySelector('.anticon-caret-right')).toBeDefined(); }); }); }); @@ -166,8 +166,12 @@ describe('collapse', () => { template: ` template - +

Panel01

@@ -201,8 +205,7 @@ export class NzTestCollapseBasicComponent {
` }) -export class NzTestCollapseTemplateComponent { -} +export class NzTestCollapseTemplateComponent {} @Component({ selector: 'nz-test-collapse-icon', @@ -223,5 +226,4 @@ export class NzTestCollapseTemplateComponent { ` }) -export class NzTestCollapseIconComponent { -} +export class NzTestCollapseIconComponent {} diff --git a/components/comment/demo/basic.ts b/components/comment/demo/basic.ts index ddb8dd854af..8e86c8d9885 100644 --- a/components/comment/demo/basic.ts +++ b/components/comment/demo/basic.ts @@ -5,29 +5,50 @@ import { distanceInWords } from 'date-fns'; selector: 'nz-demo-comment-basic', template: ` - + -

We supply a series of design principles, practical patterns and high quality design resources - (Sketch and Axure), to help people create their product prototypes beautifully and efficiently. +

+ We supply a series of design principles, practical patterns and high quality design resources (Sketch and + Axure), to help people create their product prototypes beautifully and efficiently.

- - + + - - {{dislikes}} + + {{ dislikes }} Reply to
`, - styles : [` - .count { - padding-left: 8px; - cursor: auto; - } - `] + styles: [ + ` + .count { + padding-left: 8px; + cursor: auto; + } + ` + ] }) export class NzDemoCommentBasicComponent { likes = 0; diff --git a/components/comment/demo/editor.ts b/components/comment/demo/editor.ts index 6fe84bd6aa1..40520e56caf 100644 --- a/components/comment/demo/editor.ts +++ b/components/comment/demo/editor.ts @@ -9,7 +9,7 @@ import { distanceInWords } from 'date-fns'; -

{{item.content}}

+

{{ item.content }}

@@ -28,7 +28,7 @@ import { distanceInWords } from 'date-fns'; `, - styles : [] + styles: [] }) export class NzDemoCommentEditorComponent { data: any[] = []; @@ -45,12 +45,15 @@ export class NzDemoCommentEditorComponent { this.inputValue = ''; setTimeout(() => { this.submitting = false; - this.data = [...this.data, { - ...this.user, - content, - datetime: new Date(), - displayTime: distanceInWords(new Date(), new Date()) - }].map(e => { + this.data = [ + ...this.data, + { + ...this.user, + content, + datetime: new Date(), + displayTime: distanceInWords(new Date(), new Date()) + } + ].map(e => { return { ...e, displayTime: distanceInWords(new Date(), e.datetime) @@ -58,5 +61,4 @@ export class NzDemoCommentEditorComponent { }); }, 800); } - } diff --git a/components/comment/demo/list.ts b/components/comment/demo/list.ts index 2e1ed0687b7..95606ab7cd6 100644 --- a/components/comment/demo/list.ts +++ b/components/comment/demo/list.ts @@ -9,28 +9,30 @@ import { addDays, distanceInWords } from 'date-fns'; -

{{item.content}}

+

{{ item.content }}

Reply to
`, - styles : [] + styles: [] }) export class NzDemoCommentListComponent { data = [ { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', datetime: distanceInWords(new Date(), addDays(new Date(), 1)) }, { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', datetime: distanceInWords(new Date(), addDays(new Date(), 2)) } diff --git a/components/comment/demo/nested.ts b/components/comment/demo/nested.ts index 692f0c788a5..161164b8efc 100644 --- a/components/comment/demo/nested.ts +++ b/components/comment/demo/nested.ts @@ -7,50 +7,49 @@ import { Component } from '@angular/core'; -

{{comment.content}}

+

{{ comment.content }}

Reply to - +
- - + `, - styles : [] + styles: [] }) export class NzDemoCommentNestedComponent { data = { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', children: [ { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', children: [ { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' }, { author: 'Han Solo', avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', - content: 'We supply a series of design principles, practical patterns and high quality design resources' + + content: + 'We supply a series of design principles, practical patterns and high quality design resources' + '(Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' } ] diff --git a/components/comment/nz-comment-cells.ts b/components/comment/nz-comment-cells.ts index 7ec788c5263..ff2e4e63e24 100644 --- a/components/comment/nz-comment-cells.ts +++ b/components/comment/nz-comment-cells.ts @@ -1,36 +1,36 @@ import { CdkPortalOutlet, TemplatePortal } from '@angular/cdk/portal'; import { ChangeDetectionStrategy, - Component, ComponentFactoryResolver, - Directive, Input, OnDestroy, + Component, + ComponentFactoryResolver, + Directive, + Input, + OnDestroy, OnInit, TemplateRef, ViewChild, - ViewContainerRef, ViewEncapsulation + ViewContainerRef, + ViewEncapsulation } from '@angular/core'; @Directive({ selector: 'nz-avatar[nz-comment-avatar]' }) -export class NzCommentAvatarDirective { -} +export class NzCommentAvatarDirective {} @Directive({ selector: 'nz-comment-content, [nz-comment-content]', - host : { 'class': 'ant-comment-content-detail' } + host: { class: 'ant-comment-content-detail' } }) -export class NzCommentContentDirective { -} +export class NzCommentContentDirective {} @Directive({ selector: '[nzCommentActionHost]' }) export class NzCommentActionHostDirective extends CdkPortalOutlet implements OnInit, OnDestroy { - @Input() nzCommentActionHost: TemplatePortal | null; - constructor(componentFactoryResolver: ComponentFactoryResolver, - viewContainerRef: ViewContainerRef) { + constructor(componentFactoryResolver: ComponentFactoryResolver, viewContainerRef: ViewContainerRef) { super(componentFactoryResolver, viewContainerRef); } @@ -45,10 +45,10 @@ export class NzCommentActionHostDirective extends CdkPortalOutlet implements OnI } @Component({ - selector : 'nz-comment-action', - encapsulation : ViewEncapsulation.None, + selector: 'nz-comment-action', + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - template : '' + template: '' }) export class NzCommentActionComponent implements OnInit { @ViewChild(TemplateRef) implicitContent: TemplateRef; @@ -58,9 +58,7 @@ export class NzCommentActionComponent implements OnInit { return this.contentPortal; } - constructor(private viewContainerRef: ViewContainerRef) { - - } + constructor(private viewContainerRef: ViewContainerRef) {} ngOnInit(): void { this.contentPortal = new TemplatePortal(this.implicitContent, this.viewContainerRef); diff --git a/components/comment/nz-comment.component.ts b/components/comment/nz-comment.component.ts index 549e502a6b9..0832f7662f5 100644 --- a/components/comment/nz-comment.component.ts +++ b/components/comment/nz-comment.component.ts @@ -10,15 +10,15 @@ import { import { NzCommentActionComponent as CommentAction } from './nz-comment-cells'; @Component({ - selector : 'nz-comment', - templateUrl : './nz-comment.component.html', - encapsulation : ViewEncapsulation.None, + selector: 'nz-comment', + templateUrl: './nz-comment.component.html', + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - host : { - 'class': 'ant-comment' + host: { + class: 'ant-comment' }, - styles : [ - ` + styles: [ + ` nz-comment { display: block; } @@ -30,12 +30,9 @@ import { NzCommentActionComponent as CommentAction } from './nz-comment-cells'; ] }) export class NzCommentComponent { - @Input() nzAuthor: string | TemplateRef; @Input() nzDatetime: string | TemplateRef; @ContentChildren(CommentAction) actions: QueryList; - constructor() { - } - + constructor() {} } diff --git a/components/comment/nz-comment.module.ts b/components/comment/nz-comment.module.ts index 5d17d71830f..b084b41287d 100644 --- a/components/comment/nz-comment.module.ts +++ b/components/comment/nz-comment.module.ts @@ -17,12 +17,8 @@ const NZ_COMMENT_CELLS = [ ]; @NgModule({ - imports : [ - CommonModule, - NzAddOnModule - ], - exports : [ NzCommentComponent, ...NZ_COMMENT_CELLS ], - declarations: [ NzCommentComponent, ...NZ_COMMENT_CELLS ] + imports: [CommonModule, NzAddOnModule], + exports: [NzCommentComponent, ...NZ_COMMENT_CELLS], + declarations: [NzCommentComponent, ...NZ_COMMENT_CELLS] }) -export class NzCommentModule { -} +export class NzCommentModule {} diff --git a/components/comment/nz-comment.spec.ts b/components/comment/nz-comment.spec.ts index 1a44cace537..3428ce919eb 100644 --- a/components/comment/nz-comment.spec.ts +++ b/components/comment/nz-comment.spec.ts @@ -11,19 +11,17 @@ import { NzCommentComponent } from './nz-comment.component'; import { NzCommentModule } from './nz-comment.module'; describe('NzCommentComponent', () => { - beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzCommentModule, NzListModule ], - schemas : [ NO_ERRORS_SCHEMA ], + imports: [NzCommentModule, NzListModule], + schemas: [NO_ERRORS_SCHEMA], declarations: [ NzDemoCommentBasicComponent, NzDemoCommentEditorComponent, NzDemoCommentListComponent, NzDemoCommentNestedComponent ] - }) - .compileComponents(); + }).compileComponents(); })); it('should basic work', () => { @@ -51,24 +49,36 @@ describe('NzCommentComponent', () => { expect(component.dislikes).toBe(0); expect(comment.nativeElement.classList).toContain('ant-comment'); expect(comment.nativeElement.querySelectorAll('.ant-comment-actions li>span').length).toBe(3); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe(component.likes.toString()); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe(component.dislikes.toString()); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe( + component.likes.toString() + ); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe( + component.dislikes.toString() + ); component.like(); fixture.detectChanges(); expect(component.likes).toBe(1); expect(component.dislikes).toBe(0); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe(component.likes.toString()); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe(component.dislikes.toString()); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe( + component.likes.toString() + ); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe( + component.dislikes.toString() + ); component.dislike(); fixture.detectChanges(); expect(component.likes).toBe(0); expect(component.dislikes).toBe(1); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe(component.likes.toString()); - expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe(component.dislikes.toString()); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .like').innerText).toBe( + component.likes.toString() + ); + expect(comment.nativeElement.querySelector('.ant-comment-actions li>span .dislike').innerText).toBe( + component.dislikes.toString() + ); }); it('should list work', () => { @@ -80,18 +90,17 @@ describe('NzCommentComponent', () => { expect(component.data.length === comments.length).toBeTruthy(); component.data.forEach((e, i) => { - const comment = comments[ i ]; + const comment = comments[i]; expect(comment.nativeElement.querySelector('nz-avatar[nz-comment-avatar]')).toBeTruthy(); expect(comment.nativeElement.querySelector('.ant-comment-content-author-name').innerText).toBe(e.author); expect(comment.nativeElement.querySelector('.ant-comment-content-detail p').innerText).toBe(e.content); expect(comment.nativeElement.querySelector('.ant-comment-content-author-time').innerText).toBe(e.datetime); }); - component.data = [ { ...component.data[ 0 ] } ]; + component.data = [{ ...component.data[0] }]; fixture.detectChanges(); comments = fixture.debugElement.queryAll(By.directive(NzCommentComponent)); expect(component.data.length === comments.length).toBeTruthy(); - }); it('should editor work', fakeAsync(() => { @@ -116,13 +125,12 @@ describe('NzCommentComponent', () => { comments = fixture.debugElement.queryAll(By.css('nz-list nz-comment')); component.data.forEach((e, i) => { - const comment = comments[ i ]; + const comment = comments[i]; expect(comment.nativeElement.querySelector('nz-avatar[nz-comment-avatar]')).toBeTruthy(); expect(comment.nativeElement.querySelector('.ant-comment-content-author-name').innerText).toBe(e.author); expect(comment.nativeElement.querySelector('.ant-comment-content-detail p').innerText).toBe(e.content); expect(comment.nativeElement.querySelector('.ant-comment-content-author-time').innerText).toBe(e.displayTime); }); - })); it('should nested work', () => { @@ -137,7 +145,5 @@ describe('NzCommentComponent', () => { const levelThreeComments = levelTwoComment.queryAll(By.directive(NzCommentComponent)); expect(levelThreeComments.length).toBe(2); - }); - }); diff --git a/components/date-picker/abstract-picker.component.ts b/components/date-picker/abstract-picker.component.ts index 2cdf68b9177..2cb87f20e96 100644 --- a/components/date-picker/abstract-picker.component.ts +++ b/components/date-picker/abstract-picker.component.ts @@ -21,7 +21,7 @@ import { NzI18nService } from '../i18n/nz-i18n.service'; import { CandyDate } from './lib/candy-date'; import { NzPickerComponent } from './picker.component'; -const POPUP_STYLE_PATCH = { 'position': 'relative' }; // Aim to override antd's style to support overlay's position strategy (position:absolute will cause it not working beacuse the overlay can't get the height/width of it's content) +const POPUP_STYLE_PATCH = { position: 'relative' }; // Aim to override antd's style to support overlay's position strategy (position:absolute will cause it not working beacuse the overlay can't get the height/width of it's content) /** * The base picker for all common APIs @@ -60,14 +60,17 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe protected destroyed$: Subject = new Subject(); protected isCustomPlaceHolder: boolean = false; - constructor(protected i18n: NzI18nService, protected cdr: ChangeDetectorRef, protected dateHelper: DateHelperService, public noAnimation?: NzNoAnimationDirective) { } + constructor( + protected i18n: NzI18nService, + protected cdr: ChangeDetectorRef, + protected dateHelper: DateHelperService, + public noAnimation?: NzNoAnimationDirective + ) {} ngOnInit(): void { // Subscribe the every locale change if the nzLocale is not handled by user if (!this.nzLocale) { - this.i18n.localeChange - .pipe(takeUntil(this.destroyed$)) - .subscribe(() => this.setLocale()); + this.i18n.localeChange.pipe(takeUntil(this.destroyed$)).subscribe(() => this.setLocale()); } // Default value @@ -75,7 +78,8 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe } ngOnChanges(changes: SimpleChanges): void { - if (changes.nzPopupStyle) { // Always assign the popup style patch + if (changes.nzPopupStyle) { + // Always assign the popup style patch this.nzPopupStyle = this.nzPopupStyle ? { ...this.nzPopupStyle, ...POPUP_STYLE_PATCH } : POPUP_STYLE_PATCH; } @@ -84,7 +88,8 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe this.isCustomPlaceHolder = true; } - if (changes.nzLocale) { // The nzLocale is currently handled by user + if (changes.nzLocale) { + // The nzLocale is currently handled by user this.setDefaultPlaceHolder(); } } @@ -107,7 +112,7 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe if (this.isRange) { const vAsRange = this.nzValue as CandyDate[]; if (vAsRange.length) { - this.onChangeFn([ vAsRange[ 0 ].nativeDate, vAsRange[ 1 ].nativeDate ]); + this.onChangeFn([vAsRange[0].nativeDate, vAsRange[1].nativeDate]); } else { this.onChangeFn([]); } @@ -142,11 +147,13 @@ export abstract class AbstractPickerComponent implements OnInit, OnChanges, OnDe this.cdr.markForCheck(); } - registerOnChange(fn: any): void { // tslint:disable-line:no-any + // tslint:disable-next-line:no-any + registerOnChange(fn: any): void { this.onChangeFn = fn; } - registerOnTouched(fn: any): void { // tslint:disable-line:no-any + // tslint:disable-next-line:no-any + registerOnTouched(fn: any): void { this.onTouchedFn = fn; } diff --git a/components/date-picker/date-picker.component.spec.ts b/components/date-picker/date-picker.component.spec.ts index f542c5771f7..8e4e887406e 100644 --- a/components/date-picker/date-picker.component.spec.ts +++ b/components/date-picker/date-picker.component.spec.ts @@ -28,13 +28,11 @@ describe('NzDatePickerComponent', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, NoopAnimationsModule, NzDatePickerModule, NzI18nModule ], - providers : [ + imports: [FormsModule, NoopAnimationsModule, NzDatePickerModule, NzI18nModule], + providers: [ // { provide: NZ_DATE_CONFIG, useValue: { firstDayOfWeek: 1 } } ], - declarations: [ - NzTestDatePickerComponent - ] + declarations: [NzTestDatePickerComponent] }); TestBed.compileComponents(); @@ -46,7 +44,7 @@ describe('NzDatePickerComponent', () => { debugElement = fixture.debugElement; }); - beforeEach(inject([ OverlayContainer, NzI18nService ], (oc: OverlayContainer, i18n: NzI18nService) => { + beforeEach(inject([OverlayContainer, NzI18nService], (oc: OverlayContainer, i18n: NzI18nService) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); i18nService = i18n; @@ -57,7 +55,7 @@ describe('NzDatePickerComponent', () => { }); describe('general api testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should open by click and close by click at outside', fakeAsync(() => { fixture.detectChanges(); @@ -86,7 +84,9 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect((queryFromOverlay('.ant-calendar-date-input-wrap input.ant-calendar-input') as HTMLInputElement).placeholder).toBe('Select date'); + expect( + (queryFromOverlay('.ant-calendar-date-input-wrap input.ant-calendar-input') as HTMLInputElement).placeholder + ).toBe('Select date'); expect(queryFromOverlay('.ant-calendar-table .ant-calendar-column-header-inner').textContent).toContain('Su'); })); @@ -114,7 +114,7 @@ describe('NzDatePickerComponent', () => { it('should support nzAllowClear and work properly', fakeAsync(() => { const clearBtnSelector = By.css('nz-picker i.ant-calendar-picker-clear'); - const initial = fixtureInstance.nzValue = new Date(); + const initial = (fixtureInstance.nzValue = new Date()); fixtureInstance.nzAllowClear = false; fixture.detectChanges(); expect(debugElement.query(clearBtnSelector)).toBeFalsy(); @@ -180,7 +180,7 @@ describe('NzDatePickerComponent', () => { })); it('should support nzClassName', () => { - const className = fixtureInstance.nzClassName = 'my-test-class'; + const className = (fixtureInstance.nzClassName = 'my-test-class'); fixture.detectChanges(); const picker = debugElement.queryAll(By.css('.ant-calendar-picker'))[1].nativeElement as HTMLElement; expect(picker.classList.contains(className)).toBeTruthy(); @@ -208,7 +208,7 @@ describe('NzDatePickerComponent', () => { }); it('should support nzPlaceHolder', () => { - const featureKey = fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'; + const featureKey = (fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'); fixture.detectChanges(); expect(getPickerTrigger().getAttribute('placeholder')).toBe(featureKey); }); @@ -224,7 +224,7 @@ describe('NzDatePickerComponent', () => { })); it('should support nzDropdownClassName', fakeAsync(() => { - const keyCls = fixtureInstance.nzDropdownClassName = 'my-test-class'; + const keyCls = (fixtureInstance.nzDropdownClassName = 'my-test-class'); fixture.detectChanges(); dispatchMouseEvent(getPickerTriggerWrapper(), 'click'); fixture.detectChanges(); @@ -312,14 +312,13 @@ describe('NzDatePickerComponent', () => { tick(500); fixture.detectChanges(); expect(nzOnChange).toHaveBeenCalled(); - const result = nzOnChange.calls.allArgs()[ 0 ][ 0 ]; + const result = nzOnChange.calls.allArgs()[0][0]; expect(result.getDate()).toBe(+cellText); })); - }); describe('panel switch and move forward/afterward', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support date panel changes', fakeAsync(() => { fixtureInstance.nzValue = new Date('2018-11-11'); @@ -373,13 +372,17 @@ describe('NzDatePickerComponent', () => { tick(500); fixture.detectChanges(); expect(queryFromOverlay('.ant-calendar-header .ant-calendar-month-panel')).toBeDefined(); - expect(queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2018') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2018') > -1 + ).toBeTruthy(); // Goto previous year dispatchMouseEvent(queryFromOverlay('.ant-calendar-month-panel-prev-year-btn'), 'click'); fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2017') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2017') > -1 + ).toBeTruthy(); // Goto next year * 2 dispatchMouseEvent(queryFromOverlay('.ant-calendar-month-panel-next-year-btn'), 'click'); fixture.detectChanges(); @@ -389,7 +392,9 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2019') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-month-panel-year-select-content').textContent!.indexOf('2019') > -1 + ).toBeTruthy(); // Click to choose a year to change panel dispatchMouseEvent(queryFromOverlay('td.ant-calendar-month-panel-selected-cell'), 'click'); fixture.detectChanges(); @@ -410,8 +415,12 @@ describe('NzDatePickerComponent', () => { tick(500); fixture.detectChanges(); expect(queryFromOverlay('.ant-calendar-header .ant-calendar-year-panel')).toBeDefined(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2010') > -1).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2019') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2010') > -1 + ).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2019') > -1 + ).toBeTruthy(); // Coverage for last/next cell dispatchMouseEvent(queryFromOverlay('.ant-calendar-year-panel-last-decade-cell'), 'click'); fixture.detectChanges(); @@ -426,8 +435,12 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2000') > -1).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2009') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2000') > -1 + ).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2009') > -1 + ).toBeTruthy(); // Goto next decade * 2 dispatchMouseEvent(queryFromOverlay('.ant-calendar-year-panel-next-decade-btn'), 'click'); fixture.detectChanges(); @@ -437,8 +450,12 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2020') > -1).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2029') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2020') > -1 + ).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-year-panel-decade-select-content').textContent!.indexOf('2029') > -1 + ).toBeTruthy(); // Click to choose a year to change panel dispatchMouseEvent(queryFromOverlay('td.ant-calendar-year-panel-selected-cell'), 'click'); fixture.detectChanges(); @@ -497,11 +514,10 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); expect(queryFromOverlay('.ant-calendar-header .ant-calendar-year-panel')).toBeDefined(); })); - }); // /panel switch and move forward/afterward describe('specified date picker testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support nzDateRender', fakeAsync(() => { fixtureInstance.nzDateRender = fixtureInstance.tplDateRender; @@ -515,7 +531,7 @@ describe('NzDatePickerComponent', () => { it('should support nzDateRender with typeof function', fakeAsync(() => { const featureKey = 'TEST_FIRST_DAY'; - fixtureInstance.nzDateRender = (d: Date) => d.getDate() === 1 ? featureKey : d.getDate(); + fixtureInstance.nzDateRender = (d: Date) => (d.getDate() === 1 ? featureKey : d.getDate()); fixture.detectChanges(); dispatchMouseEvent(getPickerTriggerWrapper(), 'click'); fixture.detectChanges(); @@ -540,7 +556,11 @@ describe('NzDatePickerComponent', () => { tick(500); fixture.detectChanges(); expect(queryFromOverlay('.ant-calendar-time-picker-inner.ant-calendar-time-picker-column-3')).toBeDefined(); - expect(queryFromOverlay('.ant-calendar-time-picker-select:first-child li.ant-calendar-time-picker-select-option-selected').textContent!.trim()).toBe('11'); + expect( + queryFromOverlay( + '.ant-calendar-time-picker-select:first-child li.ant-calendar-time-picker-select-option-selected' + ).textContent!.trim() + ).toBe('11'); // Click to choose a hour dispatchMouseEvent(queryFromOverlay('.ant-calendar-time-picker-select:first-child li:first-child'), 'click'); @@ -567,9 +587,9 @@ describe('NzDatePickerComponent', () => { fixtureInstance.nzShowTime = true; fixtureInstance.nzDisabledTime = () => { return { - nzDisabledHours : () => [ 0, 1, 2 ], - nzDisabledMinutes: () => [ 0, 1 ], - nzDisabledSeconds: () => [ 0 ] + nzDisabledHours: () => [0, 1, 2], + nzDisabledMinutes: () => [0, 1], + nzDisabledSeconds: () => [0] }; }; fixture.detectChanges(); @@ -580,16 +600,34 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-time-picker-select:nth-child(1) li:nth-child(3)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-time-picker-select:nth-child(2) li:nth-child(2)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-time-picker-select:nth-child(3) li:nth-child(1)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-time-picker-select:nth-child(1) li:nth-child(3)').classList.contains( + 'ant-calendar-time-picker-select-option-disabled' + ) + ).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-time-picker-select:nth-child(2) li:nth-child(2)').classList.contains( + 'ant-calendar-time-picker-select-option-disabled' + ) + ).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-time-picker-select:nth-child(3) li:nth-child(1)').classList.contains( + 'ant-calendar-time-picker-select-option-disabled' + ) + ).toBeTruthy(); // Use nzHideDisabledOptions to hide disabled times fixtureInstance.nzShowTime = { nzHideDisabledOptions: true }; fixture.detectChanges(); - expect(+queryFromOverlay('.ant-calendar-time-picker-select:nth-child(1) li:first-child').textContent!.trim()).toBe(3); - expect(+queryFromOverlay('.ant-calendar-time-picker-select:nth-child(2) li:first-child').textContent!.trim()).toBe(2); - expect(+queryFromOverlay('.ant-calendar-time-picker-select:nth-child(3) li:first-child').textContent!.trim()).toBe(1); + expect( + +queryFromOverlay('.ant-calendar-time-picker-select:nth-child(1) li:first-child').textContent!.trim() + ).toBe(3); + expect( + +queryFromOverlay('.ant-calendar-time-picker-select:nth-child(2) li:first-child').textContent!.trim() + ).toBe(2); + expect( + +queryFromOverlay('.ant-calendar-time-picker-select:nth-child(3) li:first-child').textContent!.trim() + ).toBe(1); })); it('should support nzRenderExtraFooter', fakeAsync(() => { @@ -619,7 +657,7 @@ describe('NzDatePickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - const result = nzOnChange.calls.allArgs()[ 0 ][ 0 ]; + const result = nzOnChange.calls.allArgs()[0][0]; expect(isSameDay(new Date(), result)).toBeTruthy(); expect(queryFromOverlay('.ant-calendar-picker-container')).toBeFalsy(); // Should closed })); @@ -637,7 +675,10 @@ describe('NzDatePickerComponent', () => { openPickerByClickTrigger(); // Click header to month panel - dispatchMouseEvent(overlayContainerElement.querySelector('.ant-calendar-header .ant-calendar-month-select')!, 'click'); + dispatchMouseEvent( + overlayContainerElement.querySelector('.ant-calendar-header .ant-calendar-month-select')!, + 'click' + ); fixture.detectChanges(); tick(500); fixture.detectChanges(); @@ -683,14 +724,13 @@ describe('NzDatePickerComponent', () => { flush(); fixture.detectChanges(); expect(nzOnChange).toHaveBeenCalled(); - const result = nzOnChange.calls.allArgs()[ 0 ][ 0 ]; + const result = nzOnChange.calls.allArgs()[0][0]; expect(result.getDate()).toBe(22); })); - }); // /specified date picker testing describe('ngModel value accesors', () => { - beforeEach(() => fixtureInstance.useSuite = 3); + beforeEach(() => (fixtureInstance.useSuite = 3)); it('should specified date provide by "modelValue" be choosed', fakeAsync(() => { fixtureInstance.modelValue = new Date('2018-11-11'); @@ -744,14 +784,14 @@ describe('NzDatePickerComponent', () => { tick(500); fixture.detectChanges(); } - }); @Component({ template: ` - { - + @@ -812,11 +849,9 @@ class NzTestDatePickerComponent { nzSize: string; nzStyle: NGStyleInterface; - nzOnOpenChange(): void { - } + nzOnOpenChange(): void {} - nzOnChange(): void { - } + nzOnChange(): void {} nzValue: Date | null; @@ -828,11 +863,9 @@ class NzTestDatePickerComponent { nzMode: string; // nzRanges; - nzOnPanelChange(): void { - } + nzOnPanelChange(): void {} - nzOnOk(): void { - } + nzOnOk(): void {} // --- Suite 2 nzOpen: boolean; diff --git a/components/date-picker/date-picker.component.ts b/components/date-picker/date-picker.component.ts index ea7f4207d55..a3708cb01ff 100644 --- a/components/date-picker/date-picker.component.ts +++ b/components/date-picker/date-picker.component.ts @@ -18,17 +18,18 @@ import { NzI18nService } from '../i18n/nz-i18n.service'; import { DateRangePickerComponent } from './date-range-picker.component'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-date-picker', - templateUrl : './date-range-picker.component.html', - providers : [ { - provide : NG_VALUE_ACCESSOR, - multi : true, - useExisting: forwardRef(() => NzDatePickerComponent) - } ] + selector: 'nz-date-picker', + templateUrl: './date-range-picker.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + multi: true, + useExisting: forwardRef(() => NzDatePickerComponent) + } + ] }) - export class NzDatePickerComponent extends DateRangePickerComponent { isRange: boolean = false; diff --git a/components/date-picker/date-picker.module.ts b/components/date-picker/date-picker.module.ts index e82df0ceef4..8a2d2db2718 100644 --- a/components/date-picker/date-picker.module.ts +++ b/components/date-picker/date-picker.module.ts @@ -18,14 +18,7 @@ import { NzWeekPickerComponent } from './week-picker.component'; import { NzYearPickerComponent } from './year-picker.component'; @NgModule({ - imports: [ - CommonModule, - OverlayModule, - LibPackerModule, - NzIconModule, - NzOverlayModule, - NzNoAnimationModule - ], + imports: [CommonModule, OverlayModule, LibPackerModule, NzIconModule, NzOverlayModule, NzNoAnimationModule], exports: [ NzDatePickerComponent, NzRangePickerComponent, @@ -45,4 +38,4 @@ import { NzYearPickerComponent } from './year-picker.component'; NzRangePickerComponent ] }) -export class NzDatePickerModule { } +export class NzDatePickerModule {} diff --git a/components/date-picker/date-range-picker.component.ts b/components/date-picker/date-range-picker.component.ts index 480c7913d1a..c5e0856b080 100644 --- a/components/date-picker/date-range-picker.component.ts +++ b/components/date-picker/date-range-picker.component.ts @@ -1,4 +1,14 @@ -import { ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, TemplateRef } from '@angular/core'; +import { + ChangeDetectorRef, + Component, + EventEmitter, + Input, + OnChanges, + OnInit, + Output, + SimpleChanges, + TemplateRef +} from '@angular/core'; import { NzNoAnimationDirective } from '../core/no-animation/nz-no-animation.directive'; import { FunctionProp } from '../core/types/common-wrap'; @@ -25,21 +35,29 @@ export class DateRangePickerComponent extends AbstractPickerComponent implements @Output() readonly nzOnPanelChange = new EventEmitter(); private _showTime: object | boolean; - @Input() get nzShowTime(): object | boolean { return this._showTime; } + @Input() get nzShowTime(): object | boolean { + return this._showTime; + } set nzShowTime(value: object | boolean) { this._showTime = typeof value === 'object' ? value : toBoolean(value); } @Output() readonly nzOnOk = new EventEmitter(); - get realShowToday(): boolean { // Range not support nzShowToday currently + get realShowToday(): boolean { + // Range not support nzShowToday currently return !this.isRange && this.nzShowToday; } pickerStyle: object; // Final picker style that contains width fix corrections etc. extraFooter: TemplateRef | string; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); } @@ -86,7 +104,7 @@ export class DateRangePickerComponent extends AbstractPickerComponent implements if (this.isRange) { const value = this.nzValue as CandyDate[]; if (value.length) { - this.nzOnOk.emit([ value[ 0 ].nativeDate, value[ 1 ].nativeDate ]); + this.nzOnOk.emit([value[0].nativeDate, value[1].nativeDate]); } else { this.nzOnOk.emit([]); } diff --git a/components/date-picker/demo/basic.ts b/components/date-picker/demo/basic.ts index a957180ced2..dbac78452c3 100644 --- a/components/date-picker/demo/basic.ts +++ b/components/date-picker/demo/basic.ts @@ -6,24 +6,33 @@ import { en_US, zh_CN, NzI18nService } from 'ng-zorro-antd'; selector: 'nz-demo-date-picker-basic', template: ` -
- -
+
+ +
-
+
-
+
-
+
`, - styles : [ ` - nz-date-picker, nz-month-picker, nz-year-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - ` ] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-year-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerBasicComponent { date = null; // new Date(); dateRange = []; // [ new Date(), addDays(new Date(), 3) ]; diff --git a/components/date-picker/demo/date-render.ts b/components/date-picker/demo/date-render.ts index 23d77b67855..81911389743 100644 --- a/components/date-picker/demo/date-render.ts +++ b/components/date-picker/demo/date-render.ts @@ -12,16 +12,19 @@ import { Component } from '@angular/core';
`, - styles : [ ` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - .border{ - border: 1px solid #1890ff; - border-radius: 50%; - } - ` ] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + .border { + border: 1px solid #1890ff; + border-radius: 50%; + } + ` + ] }) - -export class NzDemoDatePickerDateRenderComponent { -} +export class NzDemoDatePickerDateRenderComponent {} diff --git a/components/date-picker/demo/disabled-date.ts b/components/date-picker/demo/disabled-date.ts index b95cffd877f..e863b9bdb87 100644 --- a/components/date-picker/demo/disabled-date.ts +++ b/components/date-picker/demo/disabled-date.ts @@ -9,13 +9,14 @@ import setHours from 'date-fns/set_hours'; nzFormat="yyyy-MM-dd HH:mm:ss" [nzDisabledDate]="disabledDate" [nzDisabledTime]="disabledDateTime" - [nzShowTime]="{ nzDefaultOpenValue: timeDefaultValue }"> + [nzShowTime]="{ nzDefaultOpenValue: timeDefaultValue }" + > -
+
-
+
-
+
`, - styles : [ ` - nz-date-picker, nz-month-picker, nz-year-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - ` ] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-year-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerDisabledDateComponent { today = new Date(); timeDefaultValue = setHours(new Date(), 0); @@ -45,28 +51,28 @@ export class NzDemoDatePickerDisabledDateComponent { disabledDate = (current: Date): boolean => { // Can not select days before today and today return differenceInCalendarDays(current, this.today) > 0; - } + }; disabledDateTime = (): object => { return { - nzDisabledHours : () => this.range(0, 24).splice(4, 20), + nzDisabledHours: () => this.range(0, 24).splice(4, 20), nzDisabledMinutes: () => this.range(30, 60), - nzDisabledSeconds: () => [ 55, 56 ] + nzDisabledSeconds: () => [55, 56] }; - } + }; disabledRangeTime = (_value: Date[], type: 'start' | 'end'): object => { if (type === 'start') { return { - nzDisabledHours : () => this.range(0, 60).splice(4, 20), + nzDisabledHours: () => this.range(0, 60).splice(4, 20), nzDisabledMinutes: () => this.range(30, 60), - nzDisabledSeconds: () => [ 55, 56 ] + nzDisabledSeconds: () => [55, 56] }; } return { - nzDisabledHours : () => this.range(0, 60).splice(20, 4), + nzDisabledHours: () => this.range(0, 60).splice(20, 4), nzDisabledMinutes: () => this.range(0, 31), - nzDisabledSeconds: () => [ 55, 56 ] + nzDisabledSeconds: () => [55, 56] }; - } + }; } diff --git a/components/date-picker/demo/disabled.ts b/components/date-picker/demo/disabled.ts index ac4f11b09c7..7258452a874 100644 --- a/components/date-picker/demo/disabled.ts +++ b/components/date-picker/demo/disabled.ts @@ -4,17 +4,20 @@ import { Component } from '@angular/core'; selector: 'nz-demo-date-picker-disabled', template: ` -
+
-
+
`, - styles: [` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - `] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - -export class NzDemoDatePickerDisabledComponent { -} +export class NzDemoDatePickerDisabledComponent {} diff --git a/components/date-picker/demo/extra-footer.ts b/components/date-picker/demo/extra-footer.ts index b545c3b5ccb..c8bc8b412bb 100644 --- a/components/date-picker/demo/extra-footer.ts +++ b/components/date-picker/demo/extra-footer.ts @@ -9,13 +9,17 @@ import { Component } from '@angular/core'; `, - styles: [` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - `] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerExtraFooterComponent { plainFooter = 'plain extra footer'; footerRender = () => 'extra footer'; diff --git a/components/date-picker/demo/format.ts b/components/date-picker/demo/format.ts index 5b9232b412f..ba26e9ee0c7 100644 --- a/components/date-picker/demo/format.ts +++ b/components/date-picker/demo/format.ts @@ -4,18 +4,22 @@ import { Component } from '@angular/core'; selector: 'nz-demo-date-picker-format', template: ` -
+
-
+
`, - styles: [` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - `] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerFormatComponent { dateFormat = 'yyyy/MM/dd'; monthFormat = 'yyyy/MM'; diff --git a/components/date-picker/demo/mode.ts b/components/date-picker/demo/mode.ts index c1c4d4cce02..23b9ef9cdc6 100644 --- a/components/date-picker/demo/mode.ts +++ b/components/date-picker/demo/mode.ts @@ -7,16 +7,21 @@ import { Component } from '@angular/core'; [nzMode]="dateMode" nzShowTime (nzOnOpenChange)="handleDateOpenChange($event)" - (nzOnPanelChange)="handleDatePanelChange($event)"> + (nzOnPanelChange)="handleDatePanelChange($event)" + > `, - styles: [` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - `] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerModeComponent { dateMode = 'time'; diff --git a/components/date-picker/demo/presetted-ranges.ts b/components/date-picker/demo/presetted-ranges.ts index d7dee93aa2f..fc64f51ee7f 100644 --- a/components/date-picker/demo/presetted-ranges.ts +++ b/components/date-picker/demo/presetted-ranges.ts @@ -4,12 +4,8 @@ import endOfMonth from 'date-fns/end_of_month'; @Component({ selector: 'nz-demo-date-picker-presetted-ranges', template: ` - -
+ +
`, - styles : [ ` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - ` ] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerPresettedRangesComponent { - ranges1 = { 'Today': [ new Date(), new Date() ], 'This Month': [ new Date(), endOfMonth(new Date()) ] }; - ranges2 = { 'Today': [ new Date(), new Date() ], 'This Month': [ new Date(), endOfMonth(new Date()) ] }; + ranges1 = { Today: [new Date(), new Date()], 'This Month': [new Date(), endOfMonth(new Date())] }; + ranges2 = { Today: [new Date(), new Date()], 'This Month': [new Date(), endOfMonth(new Date())] }; onChange(result: Date[]): void { - console.log('From: ', result[ 0 ], ', to: ', result[ 1 ]); + console.log('From: ', result[0], ', to: ', result[1]); } } diff --git a/components/date-picker/demo/size.ts b/components/date-picker/demo/size.ts index f29b85e076e..d517a766918 100644 --- a/components/date-picker/demo/size.ts +++ b/components/date-picker/demo/size.ts @@ -17,13 +17,17 @@ import { Component } from '@angular/core';
`, - styles: [` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - `] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerSizeComponent { size = 'default'; } diff --git a/components/date-picker/demo/start-end.ts b/components/date-picker/demo/start-end.ts index 61821cb2406..367803e370f 100644 --- a/components/date-picker/demo/start-end.ts +++ b/components/date-picker/demo/start-end.ts @@ -10,7 +10,8 @@ import { Component } from '@angular/core'; [(ngModel)]="startValue" nzPlaceHolder="Start" (ngModelChange)="onStartChange($event)" - (nzOnOpenChange)="handleStartOpenChange($event)"> + (nzOnOpenChange)="handleStartOpenChange($event)" + > + (nzOnOpenChange)="handleEndOpenChange($event)" + > `, - styles : [ - `nz-date-picker { - margin: 0 8px 12px 0; - }` + styles: [ + ` + nz-date-picker { + margin: 0 8px 12px 0; + } + ` ] }) - export class NzDemoDatePickerStartEndComponent { startValue: Date | null = null; endValue: Date | null = null; @@ -40,14 +43,14 @@ export class NzDemoDatePickerStartEndComponent { return false; } return startValue.getTime() > this.endValue.getTime(); - } + }; disabledEndDate = (endValue: Date): boolean => { if (!endValue || !this.startValue) { return false; } return endValue.getTime() <= this.startValue.getTime(); - } + }; onStartChange(date: Date): void { this.startValue = date; diff --git a/components/date-picker/demo/time.ts b/components/date-picker/demo/time.ts index b2409dfae8a..6f8b3f83b68 100644 --- a/components/date-picker/demo/time.ts +++ b/components/date-picker/demo/time.ts @@ -10,22 +10,26 @@ import { Component } from '@angular/core'; (ngModelChange)="onChange($event)" (nzOnOk)="onOk($event)" > -
+
`, - styles : [ ` - nz-date-picker, nz-month-picker, nz-range-picker, nz-week-picker { - margin: 0 8px 12px 0; - } - ` ] + styles: [ + ` + nz-date-picker, + nz-month-picker, + nz-range-picker, + nz-week-picker { + margin: 0 8px 12px 0; + } + ` + ] }) - export class NzDemoDatePickerTimeComponent { onChange(result: Date): void { console.log('Selected Time: ', result); diff --git a/components/date-picker/header-picker.component.ts b/components/date-picker/header-picker.component.ts index 54285e10eaf..030d53770a3 100644 --- a/components/date-picker/header-picker.component.ts +++ b/components/date-picker/header-picker.component.ts @@ -29,7 +29,12 @@ export class HeaderPickerComponent extends AbstractPickerComponent implements On private supportPanels: PanelMode[]; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); } @@ -38,7 +43,7 @@ export class HeaderPickerComponent extends AbstractPickerComponent implements On this.panelMode = this.endPanelMode; - const allHeaderPanels: PanelMode[] = [ 'decade', 'year', 'month' ]; + const allHeaderPanels: PanelMode[] = ['decade', 'year', 'month']; this.supportPanels = allHeaderPanels.slice(0, allHeaderPanels.indexOf(this.endPanelMode) + 1); } @@ -53,7 +58,8 @@ export class HeaderPickerComponent extends AbstractPickerComponent implements On onPanelModeChange(mode: PanelMode): void { if (this.supportPanels.indexOf(mode) > -1) { this.panelMode = mode; - } else { // Since the default "click year" logic can be "year panel" -> "date panel", we need force to the end panel otherwise + } else { + // Since the default "click year" logic can be "year panel" -> "date panel", we need force to the end panel otherwise this.panelMode = this.endPanelMode; } } diff --git a/components/date-picker/month-picker.component.spec.ts b/components/date-picker/month-picker.component.spec.ts index d285fda1b31..e6256d12917 100644 --- a/components/date-picker/month-picker.component.spec.ts +++ b/components/date-picker/month-picker.component.spec.ts @@ -23,11 +23,9 @@ describe('NzMonthPickerComponent', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [FormsModule, NoopAnimationsModule, NzDatePickerModule, NzInputModule ], - providers : [], - declarations: [ - NzTestMonthPickerComponent - ] + imports: [FormsModule, NoopAnimationsModule, NzDatePickerModule, NzInputModule], + providers: [], + declarations: [NzTestMonthPickerComponent] }); TestBed.compileComponents(); @@ -39,7 +37,7 @@ describe('NzMonthPickerComponent', () => { debugElement = fixture.debugElement; }); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainerElement = oc.getContainerElement(); })); @@ -48,7 +46,7 @@ describe('NzMonthPickerComponent', () => { }); describe('general api testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should open by click and close by click at outside', fakeAsync(() => { fixture.detectChanges(); @@ -67,7 +65,7 @@ describe('NzMonthPickerComponent', () => { it('should support nzAllowClear and work properly', fakeAsync(() => { const clearBtnSelector = By.css('nz-picker i.ant-calendar-picker-clear'); - const initial = fixtureInstance.nzValue = new Date(); + const initial = (fixtureInstance.nzValue = new Date()); fixtureInstance.nzAllowClear = false; fixture.detectChanges(); tick(500); @@ -142,7 +140,7 @@ describe('NzMonthPickerComponent', () => { })); it('should support nzClassName', () => { - const className = fixtureInstance.nzClassName = 'my-test-class'; + const className = (fixtureInstance.nzClassName = 'my-test-class'); fixture.detectChanges(); const picker = debugElement.queryAll(By.css('.ant-calendar-picker'))[1].nativeElement as HTMLElement; expect(picker.classList.contains(className)).toBeTruthy(); @@ -172,8 +170,10 @@ describe('NzMonthPickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - const allDisabledCells = overlayContainerElement.querySelectorAll('tbody.ant-calendar-month-panel-tbody tr td.ant-calendar-month-panel-cell-disabled'); - const disabledCell = allDisabledCells[ allDisabledCells.length - 1 ]; + const allDisabledCells = overlayContainerElement.querySelectorAll( + 'tbody.ant-calendar-month-panel-tbody tr td.ant-calendar-month-panel-cell-disabled' + ); + const disabledCell = allDisabledCells[allDisabledCells.length - 1]; expect(disabledCell.textContent).toContain('11'); })); @@ -185,7 +185,7 @@ describe('NzMonthPickerComponent', () => { }); it('should support nzPlaceHolder', () => { - const featureKey = fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'; + const featureKey = (fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'); fixture.detectChanges(); expect(getPickerTrigger().getAttribute('placeholder')).toBe(featureKey); }); @@ -201,7 +201,7 @@ describe('NzMonthPickerComponent', () => { })); it('should support nzDropdownClassName', fakeAsync(() => { - const keyCls = fixtureInstance.nzDropdownClassName = 'my-test-class'; + const keyCls = (fixtureInstance.nzDropdownClassName = 'my-test-class'); fixture.detectChanges(); dispatchMouseEvent(getPickerTriggerWrapper(), 'click'); fixture.detectChanges(); @@ -266,14 +266,13 @@ describe('NzMonthPickerComponent', () => { tick(500); fixture.detectChanges(); expect(nzOnChange).toHaveBeenCalled(); - const result = nzOnChange.calls.allArgs()[ 0 ][ 0 ]; + const result = nzOnChange.calls.allArgs()[0][0]; expect(result.getMonth() + 1).toBe(parseInt(cellText, 10)); })); - }); // /general api testing describe('panel switch and move forward/afterward', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support year panel changes', fakeAsync(() => { fixtureInstance.nzValue = new Date('2018-11'); @@ -340,11 +339,10 @@ describe('NzMonthPickerComponent', () => { expect(queryFromOverlay('.ant-calendar-decade-panel-century').textContent).toContain('2100'); expect(queryFromOverlay('.ant-calendar-decade-panel-century').textContent).toContain('2199'); })); - }); // /panel switch and move forward/afterward describe('specified date picker testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support nzRenderExtraFooter', fakeAsync(() => { fixtureInstance.nzRenderExtraFooter = () => fixtureInstance.tplExtraFooter; @@ -357,11 +355,10 @@ describe('NzMonthPickerComponent', () => { fixture.detectChanges(); expect(overlayContainerElement.textContent!.indexOf(fixtureInstance.nzRenderExtraFooter) > -1).toBeTruthy(); })); - }); // /specified date picker testing describe('ngModel value accesors', () => { - beforeEach(() => fixtureInstance.useSuite = 3); + beforeEach(() => (fixtureInstance.useSuite = 3)); it('should specified date provide by "modelValue" be choosed', fakeAsync(() => { fixtureInstance.modelValue = new Date('2018-11'); @@ -400,7 +397,9 @@ describe('NzMonthPickerComponent', () => { } function getSelectedMonthCell(): HTMLElement { - return queryFromOverlay('tbody.ant-calendar-month-panel-tbody td.ant-calendar-month-panel-selected-cell') as HTMLElement; + return queryFromOverlay( + 'tbody.ant-calendar-month-panel-tbody td.ant-calendar-month-panel-selected-cell' + ) as HTMLElement; } function getFirstMonthCell(): HTMLElement { @@ -417,14 +416,14 @@ describe('NzMonthPickerComponent', () => { tick(500); fixture.detectChanges(); } - }); @Component({ template: ` - { [nzSize]="nzSize" [nzStyle]="nzStyle" (nzOnOpenChange)="nzOnOpenChange($event)" - [nzDefaultValue]="nzDefaultValue" [ngModel]="nzValue" (ngModelChange)="nzOnChange($event)" - [nzRenderExtraFooter]="nzRenderExtraFooter" > @@ -480,11 +477,9 @@ class NzTestMonthPickerComponent { nzSize: string; nzStyle: NGStyleInterface; - nzOnOpenChange(): void { - } + nzOnOpenChange(): void {} - nzOnChange(): void { - } + nzOnChange(): void {} nzValue: Date | null; diff --git a/components/date-picker/month-picker.component.ts b/components/date-picker/month-picker.component.ts index 003a5e420ef..caaa109211b 100644 --- a/components/date-picker/month-picker.component.ts +++ b/components/date-picker/month-picker.component.ts @@ -19,24 +19,31 @@ import { DateHelperService } from '../i18n/date-helper.service'; import { HeaderPickerComponent, SupportHeaderPanel } from './header-picker.component'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-month-picker', - templateUrl : './header-picker.component.html', - providers : [ { - provide : NG_VALUE_ACCESSOR, - multi : true, - useExisting: forwardRef(() => NzMonthPickerComponent) - } ] + selector: 'nz-month-picker', + templateUrl: './header-picker.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + multi: true, + useExisting: forwardRef(() => NzMonthPickerComponent) + } + ] }) - export class NzMonthPickerComponent extends HeaderPickerComponent { @Input() nzFormat: string = 'yyyy-MM'; endPanelMode: SupportHeaderPanel = 'month'; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, renderer: Renderer2, elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + renderer: Renderer2, + elementRef: ElementRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); renderer.addClass(elementRef.nativeElement, 'ant-calendar-picker'); } diff --git a/components/date-picker/picker.component.ts b/components/date-picker/picker.component.ts index e16d43ed64d..ec51a49aa9a 100644 --- a/components/date-picker/picker.component.ts +++ b/components/date-picker/picker.component.ts @@ -24,14 +24,11 @@ import { CandyDate } from './lib/candy-date'; @Component({ encapsulation: ViewEncapsulation.None, - selector : 'nz-picker', - templateUrl : './picker.component.html', - animations : [ - slideMotion - ], + selector: 'nz-picker', + templateUrl: './picker.component.html', + animations: [slideMotion], changeDetection: ChangeDetectionStrategy.OnPush }) - export class NzPickerComponent implements OnInit, AfterViewInit { @Input() noAnimation: boolean = false; @Input() isRange: boolean = false; @@ -61,26 +58,26 @@ export class NzPickerComponent implements OnInit, AfterViewInit { { // offsetX: -10, // TODO: What a pity, cdk/overlay current not support offset configs even though it already provide these properties // offsetY: -10, - originX : 'start', - originY : 'top', + originX: 'start', + originY: 'top', overlayX: 'start', overlayY: 'top' }, { - originX : 'start', - originY : 'bottom', + originX: 'start', + originY: 'bottom', overlayX: 'start', overlayY: 'bottom' }, { - originX : 'end', - originY : 'top', + originX: 'end', + originY: 'top', overlayX: 'end', overlayY: 'top' }, { - originX : 'end', - originY : 'bottom', + originX: 'end', + originY: 'bottom', overlayX: 'end', overlayY: 'bottom' } @@ -89,20 +86,21 @@ export class NzPickerComponent implements OnInit, AfterViewInit { currentPositionX: 'start' | 'end' = 'start'; currentPositionY: 'top' | 'bottom' = 'top'; - get realOpenState(): boolean { // The value that really decide the open state of overlay + get realOpenState(): boolean { + // The value that really decide the open state of overlay return this.isOpenHandledByUser() ? !!this.open : this.overlayOpen; } - constructor(private dateHelper: DateHelperService, private changeDetector: ChangeDetectorRef) { - } + constructor(private dateHelper: DateHelperService, private changeDetector: ChangeDetectorRef) {} - ngOnInit(): void { - } + ngOnInit(): void {} ngAfterViewInit(): void { if (this.autoFocus) { if (this.isRange) { - const firstInput = (this.pickerInput.nativeElement as HTMLElement).querySelector('input:first-child') as HTMLInputElement; + const firstInput = (this.pickerInput.nativeElement as HTMLElement).querySelector( + 'input:first-child' + ) as HTMLInputElement; firstInput.focus(); // Focus on the first input } else { this.pickerInput.nativeElement.focus(); @@ -166,7 +164,7 @@ export class NzPickerComponent implements OnInit, AfterViewInit { getReadableValue(partType?: RangePartType): string | null { let value: CandyDate; if (this.isRange) { - value = (this.value as CandyDate[])[ this.getPartTypeIndex(partType as RangePartType) ]; + value = (this.value as CandyDate[])[this.getPartTypeIndex(partType as RangePartType)]; } else { value = this.value as CandyDate; } @@ -174,20 +172,18 @@ export class NzPickerComponent implements OnInit, AfterViewInit { } getPartTypeIndex(partType: RangePartType): number { - return { 'left': 0, 'right': 1 }[ partType ]; + return { left: 0, right: 1 }[partType]; } getPlaceholder(partType?: RangePartType): string { - return this.isRange - ? this.placeholder[ this.getPartTypeIndex(partType!) ] - : this.placeholder as string; + return this.isRange ? this.placeholder[this.getPartTypeIndex(partType!)] : (this.placeholder as string); } isEmptyValue(value: CandyDate[] | CandyDate | null): boolean { if (value === null) { return true; } else if (this.isRange) { - return !value || !Array.isArray(value) || value.every((val) => !val); + return !value || !Array.isArray(value) || value.every(val => !val); } else { return !value; } diff --git a/components/date-picker/range-picker.component.spec.ts b/components/date-picker/range-picker.component.spec.ts index e1a6d148564..069bb132e23 100644 --- a/components/date-picker/range-picker.component.spec.ts +++ b/components/date-picker/range-picker.component.spec.ts @@ -25,11 +25,9 @@ describe('NzRangePickerComponent', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports: [ FormsModule, NoopAnimationsModule, NzDatePickerModule ], + imports: [FormsModule, NoopAnimationsModule, NzDatePickerModule], providers: [], - declarations: [ - NzTestRangePickerComponent - ] + declarations: [NzTestRangePickerComponent] }); TestBed.compileComponents(); @@ -41,7 +39,7 @@ describe('NzRangePickerComponent', () => { debugElement = fixture.debugElement; }); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); @@ -51,7 +49,7 @@ describe('NzRangePickerComponent', () => { }); describe('general api testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should open by click and close by click at outside', fakeAsync(() => { fixture.detectChanges(); @@ -70,7 +68,7 @@ describe('NzRangePickerComponent', () => { it('should support nzAllowClear and work properly', fakeAsync(() => { const clearBtnSelector = By.css('nz-picker i.ant-calendar-picker-clear'); - const initial = fixtureInstance.modelValue = [ new Date(), new Date() ]; + const initial = (fixtureInstance.modelValue = [new Date(), new Date()]); fixtureInstance.nzAllowClear = false; fixture.detectChanges(); expect(debugElement.query(clearBtnSelector)).toBeNull(); @@ -98,7 +96,7 @@ describe('NzRangePickerComponent', () => { it('should support nzDisabled', fakeAsync(() => { // Make sure picker clear button shown up fixtureInstance.nzAllowClear = true; - fixtureInstance.modelValue = [ new Date(), new Date() ]; + fixtureInstance.modelValue = [new Date(), new Date()]; fixtureInstance.nzDisabled = true; fixture.detectChanges(); @@ -135,7 +133,7 @@ describe('NzRangePickerComponent', () => { })); it('should support nzClassName', () => { - const className = fixtureInstance.nzClassName = 'my-test-class'; + const className = (fixtureInstance.nzClassName = 'my-test-class'); fixture.detectChanges(); const picker = debugElement.queryAll(By.css('.ant-calendar-picker'))[1].nativeElement as HTMLElement; expect(picker.classList.contains(className)).toBeTruthy(); @@ -144,7 +142,7 @@ describe('NzRangePickerComponent', () => { it('should support nzDisabledDate', fakeAsync(() => { fixture.detectChanges(); const compareDate = new Date('2018-11-15 00:00:00'); - fixtureInstance.modelValue = [ new Date('2018-11-11 12:12:12'), null ]; + fixtureInstance.modelValue = [new Date('2018-11-11 12:12:12'), null]; fixtureInstance.nzDisabledDate = (current: Date) => isSameDay(current, compareDate); fixture.detectChanges(); @@ -152,22 +150,32 @@ describe('NzRangePickerComponent', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - const disabledCell = queryFromOverlay('.ant-calendar-range-left tbody.ant-calendar-tbody td.ant-calendar-disabled-cell'); + const disabledCell = queryFromOverlay( + '.ant-calendar-range-left tbody.ant-calendar-tbody td.ant-calendar-disabled-cell' + ); expect(disabledCell.textContent!.trim()).toBe('15'); })); it('should support nzLocale', () => { const featureKey = 'LEFT_PLACEHOLDER'; - fixtureInstance.nzLocale = { lang: { rangePlaceholder: [ featureKey, 'End' ] } }; + fixtureInstance.nzLocale = { lang: { rangePlaceholder: [featureKey, 'End'] } }; fixture.detectChanges(); - expect(getPickerTrigger().querySelector('input:nth-of-type(1)')!.getAttribute('placeholder')).toBe(featureKey); + expect( + getPickerTrigger() + .querySelector('input:nth-of-type(1)')! + .getAttribute('placeholder') + ).toBe(featureKey); }); it('should support nzPlaceHolder', () => { const featureKey = 'RIGHT_PLACEHOLDER'; - fixtureInstance.nzPlaceHolder = [ 'Start', featureKey ]; + fixtureInstance.nzPlaceHolder = ['Start', featureKey]; fixture.detectChanges(); - expect(getPickerTrigger().querySelector('input:nth-of-type(2)')!.getAttribute('placeholder')).toBe(featureKey); + expect( + getPickerTrigger() + .querySelector('input:nth-of-type(2)')! + .getAttribute('placeholder') + ).toBe(featureKey); }); it('should support nzPopupStyle', fakeAsync(() => { @@ -181,7 +189,7 @@ describe('NzRangePickerComponent', () => { })); it('should support nzDropdownClassName', fakeAsync(() => { - const keyCls = fixtureInstance.nzDropdownClassName = 'my-test-class'; + const keyCls = (fixtureInstance.nzDropdownClassName = 'my-test-class'); fixture.detectChanges(); dispatchMouseEvent(getPickerTriggerWrapper(), 'click'); fixture.detectChanges(); @@ -224,14 +232,14 @@ describe('NzRangePickerComponent', () => { })); it('should support nzValue', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11'), new Date('2018-12-11') ]; + fixtureInstance.modelValue = [new Date('2018-11-11'), new Date('2018-12-11')]; fixture.detectChanges(); openPickerByClickTrigger(); expect(getFirstSelectedDayCell().textContent!.trim()).toBe('11'); })); it('should support nzOnChange', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11'), new Date('2018-11-11') ]; + fixtureInstance.modelValue = [new Date('2018-11-11'), new Date('2018-11-11')]; const nzOnChange = spyOn(fixtureInstance, 'modelValueChange'); fixture.detectChanges(); openPickerByClickTrigger(); @@ -253,42 +261,48 @@ describe('NzRangePickerComponent', () => { expect(result[0].getDate()).toBe(+leftText); expect(result[1].getDate()).toBe(+rightText); })); - }); // /general api testing describe('panel switch and move forward/afterward', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support date panel changes', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-6-11'), new Date('2018-12-12') ]; + fixtureInstance.modelValue = [new Date('2018-6-11'), new Date('2018-12-12')]; fixture.detectChanges(); openPickerByClickTrigger(); // Click previous year button dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-prev-year-btn'), 'click'); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-year-select').textContent!.indexOf('2017') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-year-select').textContent!.indexOf('2017') > -1 + ).toBeTruthy(); // Click next year button * 2 dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-next-year-btn'), 'click'); fixture.detectChanges(); dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-next-year-btn'), 'click'); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-year-select').textContent!.indexOf('2019') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-year-select').textContent!.indexOf('2019') > -1 + ).toBeTruthy(); // Click previous month button dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-prev-month-btn'), 'click'); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-month-select').textContent!.indexOf('5') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-month-select').textContent!.indexOf('5') > -1 + ).toBeTruthy(); // Click next month button * 2 dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-next-month-btn'), 'click'); fixture.detectChanges(); dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-next-month-btn'), 'click'); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-month-select').textContent!.indexOf('7') > -1).toBeTruthy(); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-month-select').textContent!.indexOf('7') > -1 + ).toBeTruthy(); })); - }); // /panel switch and move forward/afterward describe('specified date picker testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support nzDateRender', fakeAsync(() => { fixtureInstance.nzDateRender = fixtureInstance.tplDateRender; @@ -299,14 +313,14 @@ describe('NzRangePickerComponent', () => { it('should support nzDateRender with typeof function', fakeAsync(() => { const featureKey = 'TEST_FIRST_DAY'; - fixtureInstance.nzDateRender = (d: CandyDate) => d.getDate() === 1 ? featureKey : d.getDate(); + fixtureInstance.nzDateRender = (d: CandyDate) => (d.getDate() === 1 ? featureKey : d.getDate()); fixture.detectChanges(); openPickerByClickTrigger(); expect(overlayContainerElement.textContent!.indexOf(featureKey) > -1).toBeTruthy(); })); it('should support nzShowTime', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11 11:22:33'), new Date('2018-12-12 11:22:33') ]; + fixtureInstance.modelValue = [new Date('2018-11-11 11:22:33'), new Date('2018-12-12 11:22:33')]; fixtureInstance.nzShowTime = true; fixture.detectChanges(); openPickerByClickTrigger(); @@ -318,17 +332,28 @@ describe('NzRangePickerComponent', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-inner.ant-calendar-time-picker-column-3')).toBeDefined(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:first-child li.ant-calendar-time-picker-select-option-selected').textContent!.trim()).toBe('11'); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-inner.ant-calendar-time-picker-column-3') + ).toBeDefined(); + expect( + queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:first-child li.ant-calendar-time-picker-select-option-selected' + ).textContent!.trim() + ).toBe('11'); // Click to choose a hour - dispatchMouseEvent(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:first-child li:first-child'), 'click'); - fixture.detectChanges(); - expect((queryFromOverlay('.ant-calendar-range-left input.ant-calendar-input') as HTMLInputElement).value).toBe('2018-11-11 00:22:33'); + dispatchMouseEvent( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:first-child li:first-child'), + 'click' + ); + fixture.detectChanges(); + expect((queryFromOverlay('.ant-calendar-range-left input.ant-calendar-input') as HTMLInputElement).value).toBe( + '2018-11-11 00:22:33' + ); })); it('should support nzShowTime.nzFormat', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11'), new Date('2018-12-12') ]; + fixtureInstance.modelValue = [new Date('2018-11-11'), new Date('2018-12-12')]; fixtureInstance.nzShowTime = { nzFormat: 'HH:mm' }; fixture.detectChanges(); openPickerByClickTrigger(); @@ -338,22 +363,26 @@ describe('NzRangePickerComponent', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-inner.ant-calendar-time-picker-column-2')).toBeDefined(); + expect( + queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-inner.ant-calendar-time-picker-column-2') + ).toBeDefined(); })); it('should support nzDisabledTime and nzShowTime.nzHideDisabledOptions', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11 11:11:11'), new Date('2018-12-12 12:12:12') ]; + fixtureInstance.modelValue = [new Date('2018-11-11 11:11:11'), new Date('2018-12-12 12:12:12')]; fixtureInstance.nzShowTime = true; fixtureInstance.nzDisabledTime = (_current: Date, partial: 'start' | 'end') => { - return partial === 'start' ? { - nzDisabledHours: () => [ 0, 1, 2], - nzDisabledMinutes: () => [ 0, 1 ], - nzDisabledSeconds: () => [ 0 ] - } : { - nzDisabledHours: () => [ 0, 1, 2, 3 ], - nzDisabledMinutes: () => [ 0, 1, 2 ], - nzDisabledSeconds: () => [ 0, 1 ] - }; + return partial === 'start' + ? { + nzDisabledHours: () => [0, 1, 2], + nzDisabledMinutes: () => [0, 1], + nzDisabledSeconds: () => [0] + } + : { + nzDisabledHours: () => [0, 1, 2, 3], + nzDisabledMinutes: () => [0, 1, 2], + nzDisabledSeconds: () => [0, 1] + }; }; fixture.detectChanges(); openPickerByClickTrigger(); @@ -364,25 +393,73 @@ describe('NzRangePickerComponent', () => { tick(); fixture.detectChanges(); // Left time picker - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(1) li:nth-child(3)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(2) li:nth-child(2)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(3) li:nth-child(1)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(1) li:nth-child(3)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(2) li:nth-child(2)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(3) li:nth-child(1)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); // Right time picker - expect(queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(1) li:nth-child(4)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(2) li:nth-child(3)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); - expect(queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(3) li:nth-child(2)').classList.contains('ant-calendar-time-picker-select-option-disabled')).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(1) li:nth-child(4)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(2) li:nth-child(3)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); + expect( + queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(3) li:nth-child(2)' + ).classList.contains('ant-calendar-time-picker-select-option-disabled') + ).toBeTruthy(); // Use nzHideDisabledOptions to hide disabled times fixtureInstance.nzShowTime = { nzHideDisabledOptions: true }; fixture.detectChanges(); // Left time picker - expect(+queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(1) li:first-child').textContent!.trim()).toBe(3); - expect(+queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(2) li:first-child').textContent!.trim()).toBe(2); - expect(+queryFromOverlay('.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(3) li:first-child').textContent!.trim()).toBe(1); + expect( + +queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(1) li:first-child' + ).textContent!.trim() + ).toBe(3); + expect( + +queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(2) li:first-child' + ).textContent!.trim() + ).toBe(2); + expect( + +queryFromOverlay( + '.ant-calendar-range-left .ant-calendar-time-picker-select:nth-child(3) li:first-child' + ).textContent!.trim() + ).toBe(1); // Right time picker - expect(+queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(1) li:first-child').textContent!.trim()).toBe(4); - expect(+queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(2) li:first-child').textContent!.trim()).toBe(3); - expect(+queryFromOverlay('.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(3) li:first-child').textContent!.trim()).toBe(2); + expect( + +queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(1) li:first-child' + ).textContent!.trim() + ).toBe(4); + expect( + +queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(2) li:first-child' + ).textContent!.trim() + ).toBe(3); + expect( + +queryFromOverlay( + '.ant-calendar-range-right .ant-calendar-time-picker-select:nth-child(3) li:first-child' + ).textContent!.trim() + ).toBe(2); })); it('should support nzRenderExtraFooter', fakeAsync(() => { @@ -398,13 +475,17 @@ describe('NzRangePickerComponent', () => { })); it('should support nzMode', fakeAsync(() => { - fixtureInstance.nzMode = [ 'month', 'year' ]; + fixtureInstance.nzMode = ['month', 'year']; fixture.detectChanges(); openPickerByClickTrigger(); // Left panel - expect(overlayContainerElement.querySelector('.ant-calendar-range-left .ant-calendar-header .ant-calendar-month-panel')).toBeDefined(); + expect( + overlayContainerElement.querySelector('.ant-calendar-range-left .ant-calendar-header .ant-calendar-month-panel') + ).toBeDefined(); // Right panel - expect(overlayContainerElement.querySelector('.ant-calendar-range-right .ant-calendar-header .ant-calendar-year-panel')).toBeDefined(); + expect( + overlayContainerElement.querySelector('.ant-calendar-range-right .ant-calendar-header .ant-calendar-year-panel') + ).toBeDefined(); })); it('should support nzOnPanelChange', fakeAsync(() => { @@ -414,17 +495,27 @@ describe('NzRangePickerComponent', () => { // Click header to month panel // Left - dispatchMouseEvent(overlayContainerElement.querySelector('.ant-calendar-range-left .ant-calendar-header .ant-calendar-month-select')!, 'click'); + dispatchMouseEvent( + overlayContainerElement.querySelector( + '.ant-calendar-range-left .ant-calendar-header .ant-calendar-month-select' + )!, + 'click' + ); fixture.detectChanges(); // Right - dispatchMouseEvent(overlayContainerElement.querySelector('.ant-calendar-range-right .ant-calendar-header .ant-calendar-year-select')!, 'click'); - fixture.detectChanges(); - expect(fixtureInstance.nzOnPanelChange).toHaveBeenCalledWith([ 'month', 'year' ]); + dispatchMouseEvent( + overlayContainerElement.querySelector( + '.ant-calendar-range-right .ant-calendar-header .ant-calendar-year-select' + )!, + 'click' + ); + fixture.detectChanges(); + expect(fixtureInstance.nzOnPanelChange).toHaveBeenCalledWith(['month', 'year']); })); it('should support nzOnOk', fakeAsync(() => { spyOn(fixtureInstance, 'nzOnOk'); - fixtureInstance.modelValue = [ new Date('2018-11-11 11:22:33'), new Date('2018-12-12 11:22:33') ]; + fixtureInstance.modelValue = [new Date('2018-11-11 11:22:33'), new Date('2018-12-12 11:22:33')]; fixtureInstance.nzShowTime = true; fixture.detectChanges(); openPickerByClickTrigger(); @@ -437,7 +528,7 @@ describe('NzRangePickerComponent', () => { })); it('should select date from start to end with side effects', fakeAsync(() => { - const initial = fixtureInstance.modelValue = [ new Date('2018-05-15'), new Date('2018-06-15') ]; + const initial = (fixtureInstance.modelValue = [new Date('2018-05-15'), new Date('2018-06-15')]); fixtureInstance.nzDisabledDate = (current: Date) => differenceInDays(current, initial[0]) < 0; fixtureInstance.nzShowTime = true; fixture.detectChanges(); @@ -467,7 +558,7 @@ describe('NzRangePickerComponent', () => { })); it('should display expected date when the range values are the same day (include the scenario of timepicker)', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-05-15'), new Date('2018-05-15') ]; + fixtureInstance.modelValue = [new Date('2018-05-15'), new Date('2018-05-15')]; fixtureInstance.nzShowTime = true; fixture.detectChanges(); openPickerByClickTrigger(); @@ -484,7 +575,7 @@ describe('NzRangePickerComponent', () => { it('should support nzRanges', fakeAsync(() => { const today = new Date(); - fixtureInstance.nzRanges = { 'Today': [ today, today ] }; + fixtureInstance.nzRanges = { Today: [today, today] }; fixture.detectChanges(); openPickerByClickTrigger(); expect(queryFromOverlay('.ant-calendar-range-quick-selector')).toBeDefined(); @@ -494,7 +585,9 @@ describe('NzRangePickerComponent', () => { selector = queryFromOverlay('.ant-calendar-range-quick-selector > a'); dispatchMouseEvent(selector, 'mouseenter'); fixture.detectChanges(); - expect(queryFromOverlay('.ant-calendar-range-left td.ant-calendar-selected-day').textContent).toContain(`${today.getDate()}`); + expect(queryFromOverlay('.ant-calendar-range-left td.ant-calendar-selected-day').textContent).toContain( + `${today.getDate()}` + ); selector = queryFromOverlay('.ant-calendar-range-quick-selector > a'); dispatchMouseEvent(selector, 'mouseleave'); @@ -527,14 +620,13 @@ describe('NzRangePickerComponent', () => { expect(result[0].getDate()).toBe(11); expect(result[1].getDate()).toBe(12); })); - }); // /specified date picker testing describe('ngModel value accesors', () => { - beforeEach(() => fixtureInstance.useSuite = 3); + beforeEach(() => (fixtureInstance.useSuite = 3)); it('should specified date provide by "modelValue" be choosed', fakeAsync(() => { - fixtureInstance.modelValue = [ new Date('2018-11-11'), new Date('2018-12-12') ]; + fixtureInstance.modelValue = [new Date('2018-11-11'), new Date('2018-12-12')]; fixture.detectChanges(); tick(); // Wait writeValue() tobe done fixture.detectChanges(); @@ -577,12 +669,14 @@ describe('NzRangePickerComponent', () => { } function getFirstCell(partial: 'left' | 'right'): HTMLElement { - return queryFromOverlay(`.ant-calendar-range-${partial} tbody.ant-calendar-tbody td.ant-calendar-cell`) as HTMLElement; + return queryFromOverlay( + `.ant-calendar-range-${partial} tbody.ant-calendar-tbody td.ant-calendar-cell` + ) as HTMLElement; } function getLastCell(partial: 'left' | 'right'): HTMLElement { const allCells = overlayContainerElement.querySelectorAll(`.ant-calendar-range-${partial} td.ant-calendar-cell`); - return allCells[ allCells.length - 1 ] as HTMLElement; + return allCells[allCells.length - 1] as HTMLElement; } function queryFromOverlay(selector: string): HTMLElement { @@ -601,7 +695,8 @@ describe('NzRangePickerComponent', () => { template: ` - { (nzOnOpenChange)="nzOnOpenChange($event)" [(ngModel)]="modelValue" (ngModelChange)="modelValueChange($event)" - [nzDateRender]="nzDateRender" [nzDisabledTime]="nzDisabledTime" [nzRenderExtraFooter]="nzRenderExtraFooter" @@ -660,9 +754,9 @@ class NzTestRangePickerComponent { nzDropdownClassName: string; nzSize: string; nzStyle: NGStyleInterface; - nzOnOpenChange(): void { } + nzOnOpenChange(): void {} modelValue: Array; - modelValueChange(): void { } + modelValueChange(): void {} nzDateRender: any; // tslint:disable-line:no-any nzShowTime: boolean | object = false; diff --git a/components/date-picker/range-picker.component.ts b/components/date-picker/range-picker.component.ts index f2ac84866a8..e5d89371b5d 100644 --- a/components/date-picker/range-picker.component.ts +++ b/components/date-picker/range-picker.component.ts @@ -18,22 +18,29 @@ import { DateHelperService } from '../i18n/date-helper.service'; import { DateRangePickerComponent } from './date-range-picker.component'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-range-picker', - templateUrl : './date-range-picker.component.html', - providers : [ { - provide : NG_VALUE_ACCESSOR, - multi : true, - useExisting: forwardRef(() => NzRangePickerComponent) - } ] + selector: 'nz-range-picker', + templateUrl: './date-range-picker.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + multi: true, + useExisting: forwardRef(() => NzRangePickerComponent) + } + ] }) - export class NzRangePickerComponent extends DateRangePickerComponent { isRange: boolean = true; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, renderer: Renderer2, elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + renderer: Renderer2, + elementRef: ElementRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); renderer.addClass(elementRef.nativeElement, 'ant-calendar-picker'); } diff --git a/components/date-picker/standard-types.ts b/components/date-picker/standard-types.ts index fa542a26998..9b2e0d7e811 100644 --- a/components/date-picker/standard-types.ts +++ b/components/date-picker/standard-types.ts @@ -39,7 +39,7 @@ export interface SupportTimeOptions { } export interface PresetRanges { - [ key: string ]: Date[]; + [key: string]: Date[]; } export type PanelMode = 'decade' | 'year' | 'month' | 'date' | 'time'; diff --git a/components/date-picker/week-picker.component.spec.ts b/components/date-picker/week-picker.component.spec.ts index 911bce2e00e..2602fb17a82 100644 --- a/components/date-picker/week-picker.component.spec.ts +++ b/components/date-picker/week-picker.component.spec.ts @@ -16,14 +16,14 @@ describe('NzWeekPickerComponent', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzDatePickerModule ], - declarations: [ NzTestWeekPickerComponent ] + imports: [NoopAnimationsModule, NzDatePickerModule], + declarations: [NzTestWeekPickerComponent] }); TestBed.compileComponents(); })); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); @@ -62,7 +62,6 @@ describe('NzWeekPickerComponent', () => { dispatchMouseEvent(getPickerTrigger(), 'click'); fixture.detectChanges(); } - }); @Component({ diff --git a/components/date-picker/week-picker.component.ts b/components/date-picker/week-picker.component.ts index c142800824d..b1958337e33 100644 --- a/components/date-picker/week-picker.component.ts +++ b/components/date-picker/week-picker.component.ts @@ -18,22 +18,29 @@ import { DateHelperService } from '../i18n/date-helper.service'; import { DateRangePickerComponent } from './date-range-picker.component'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-week-picker', - templateUrl : './date-range-picker.component.html', - providers : [ { - provide : NG_VALUE_ACCESSOR, - multi : true, - useExisting: forwardRef(() => NzWeekPickerComponent) - } ] + selector: 'nz-week-picker', + templateUrl: './date-range-picker.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + multi: true, + useExisting: forwardRef(() => NzWeekPickerComponent) + } + ] }) - export class NzWeekPickerComponent extends DateRangePickerComponent { showWeek: boolean = true; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, renderer: Renderer2, elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + renderer: Renderer2, + elementRef: ElementRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); renderer.addClass(elementRef.nativeElement, 'ant-calendar-picker'); } diff --git a/components/date-picker/year-picker.component.spec.ts b/components/date-picker/year-picker.component.spec.ts index 428340ef61e..18545546b7b 100644 --- a/components/date-picker/year-picker.component.spec.ts +++ b/components/date-picker/year-picker.component.spec.ts @@ -18,11 +18,9 @@ describe('NzYearPickerComponent', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, NoopAnimationsModule, NzDatePickerModule, NzInputModule ], - providers : [], - declarations: [ - NzTestYearPickerComponent - ] + imports: [FormsModule, NoopAnimationsModule, NzDatePickerModule, NzInputModule], + providers: [], + declarations: [NzTestYearPickerComponent] }); TestBed.compileComponents(); @@ -34,7 +32,7 @@ describe('NzYearPickerComponent', () => { debugElement = fixture.debugElement; }); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainerElement = oc.getContainerElement(); })); @@ -43,7 +41,7 @@ describe('NzYearPickerComponent', () => { }); describe('general api testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should open by click and close by click at outside', fakeAsync(() => { fixture.detectChanges(); @@ -62,7 +60,7 @@ describe('NzYearPickerComponent', () => { it('should support nzAllowClear and work properly', fakeAsync(() => { const clearBtnSelector = By.css('nz-picker i.ant-calendar-picker-clear'); - const initial = fixtureInstance.nzValue = new Date(); + const initial = (fixtureInstance.nzValue = new Date()); fixtureInstance.nzAllowClear = false; fixture.detectChanges(); tick(500); @@ -137,7 +135,7 @@ describe('NzYearPickerComponent', () => { })); it('should support nzClassName', () => { - const className = fixtureInstance.nzClassName = 'my-test-class'; + const className = (fixtureInstance.nzClassName = 'my-test-class'); fixture.detectChanges(); const picker = debugElement.queryAll(By.css('.ant-calendar-picker'))[1].nativeElement as HTMLElement; expect(picker.classList.contains(className)).toBeTruthy(); @@ -166,7 +164,9 @@ describe('NzYearPickerComponent', () => { fixture.detectChanges(); tick(500); fixture.detectChanges(); - const disabledCell = overlayContainerElement.querySelector('tbody.ant-calendar-year-panel-tbody tr td.ant-calendar-year-panel-cell-disabled')!; + const disabledCell = overlayContainerElement.querySelector( + 'tbody.ant-calendar-year-panel-tbody tr td.ant-calendar-year-panel-cell-disabled' + )!; expect(disabledCell.textContent).toContain('2013'); })); @@ -178,7 +178,7 @@ describe('NzYearPickerComponent', () => { }); it('should support nzPlaceHolder', () => { - const featureKey = fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'; + const featureKey = (fixtureInstance.nzPlaceHolder = 'TEST_PLACEHOLDER'); fixture.detectChanges(); expect(getPickerTrigger().getAttribute('placeholder')).toBe(featureKey); }); @@ -194,7 +194,7 @@ describe('NzYearPickerComponent', () => { })); it('should support nzDropdownClassName', fakeAsync(() => { - const keyCls = fixtureInstance.nzDropdownClassName = 'my-test-class'; + const keyCls = (fixtureInstance.nzDropdownClassName = 'my-test-class'); fixture.detectChanges(); dispatchMouseEvent(getPickerTriggerWrapper(), 'click'); fixture.detectChanges(); @@ -259,14 +259,13 @@ describe('NzYearPickerComponent', () => { tick(500); fixture.detectChanges(); expect(nzOnChange).toHaveBeenCalled(); - const result = nzOnChange.calls.allArgs()[ 0 ][ 0 ]; + const result = nzOnChange.calls.allArgs()[0][0]; expect(result.getFullYear()).toBe(parseInt(cellText, 10)); })); - }); // /general api testing describe('panel switch and move forward/afterward', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support decade panel changes', fakeAsync(() => { fixtureInstance.nzValue = new Date('2018-11'); @@ -297,11 +296,10 @@ describe('NzYearPickerComponent', () => { expect(queryFromOverlay('.ant-calendar-decade-panel-century').textContent).toContain('2100'); expect(queryFromOverlay('.ant-calendar-decade-panel-century').textContent).toContain('2199'); })); - }); // /panel switch and move forward/afterward describe('specified date picker testing', () => { - beforeEach(() => fixtureInstance.useSuite = 1); + beforeEach(() => (fixtureInstance.useSuite = 1)); it('should support nzRenderExtraFooter', fakeAsync(() => { fixtureInstance.nzRenderExtraFooter = () => fixtureInstance.tplExtraFooter; @@ -314,11 +312,10 @@ describe('NzYearPickerComponent', () => { fixture.detectChanges(); expect(overlayContainerElement.textContent!.indexOf(fixtureInstance.nzRenderExtraFooter) > -1).toBeTruthy(); })); - }); // /specified date picker testing describe('ngModel value accesors', () => { - beforeEach(() => fixtureInstance.useSuite = 3); + beforeEach(() => (fixtureInstance.useSuite = 3)); it('should specified date provide by "modelValue" be choosed', fakeAsync(() => { fixtureInstance.modelValue = new Date('2018-11'); @@ -357,11 +354,15 @@ describe('NzYearPickerComponent', () => { } function getSelectedYearCell(): HTMLElement { - return queryFromOverlay('tbody.ant-calendar-year-panel-tbody td.ant-calendar-year-panel-selected-cell') as HTMLElement; + return queryFromOverlay( + 'tbody.ant-calendar-year-panel-tbody td.ant-calendar-year-panel-selected-cell' + ) as HTMLElement; } function getSecondYearCell(): HTMLElement { - return queryFromOverlay('tbody.ant-calendar-year-panel-tbody td.ant-calendar-year-panel-cell:nth-child(2)') as HTMLElement; + return queryFromOverlay( + 'tbody.ant-calendar-year-panel-tbody td.ant-calendar-year-panel-cell:nth-child(2)' + ) as HTMLElement; } function queryFromOverlay(selector: string): HTMLElement { @@ -374,14 +375,14 @@ describe('NzYearPickerComponent', () => { tick(500); fixture.detectChanges(); } - }); @Component({ template: ` - { [nzSize]="nzSize" [nzStyle]="nzStyle" (nzOnOpenChange)="nzOnOpenChange($event)" - [nzDefaultValue]="nzDefaultValue" [ngModel]="nzValue" (ngModelChange)="nzOnChange($event)" - [nzRenderExtraFooter]="nzRenderExtraFooter" > @@ -417,7 +416,6 @@ describe('NzYearPickerComponent', () => { - ` }) @@ -438,11 +436,9 @@ class NzTestYearPickerComponent { nzSize: string; nzStyle: NGStyleInterface; - nzOnOpenChange(): void { - } + nzOnOpenChange(): void {} - nzOnChange(): void { - } + nzOnChange(): void {} nzValue: Date | null; diff --git a/components/date-picker/year-picker.component.ts b/components/date-picker/year-picker.component.ts index 36384ae6a90..9502e0fe0bd 100644 --- a/components/date-picker/year-picker.component.ts +++ b/components/date-picker/year-picker.component.ts @@ -19,24 +19,31 @@ import { DateHelperService } from '../i18n/date-helper.service'; import { HeaderPickerComponent, SupportHeaderPanel } from './header-picker.component'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-year-picker', - templateUrl : './header-picker.component.html', - providers : [ { - provide : NG_VALUE_ACCESSOR, - multi : true, - useExisting: forwardRef(() => NzYearPickerComponent) - } ] + selector: 'nz-year-picker', + templateUrl: './header-picker.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + multi: true, + useExisting: forwardRef(() => NzYearPickerComponent) + } + ] }) - export class NzYearPickerComponent extends HeaderPickerComponent { @Input() nzFormat: string = 'yyyy'; endPanelMode: SupportHeaderPanel = 'year'; - constructor(i18n: NzI18nService, cdr: ChangeDetectorRef, dateHelper: DateHelperService, renderer: Renderer2, elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + i18n: NzI18nService, + cdr: ChangeDetectorRef, + dateHelper: DateHelperService, + renderer: Renderer2, + elementRef: ElementRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { super(i18n, cdr, dateHelper, noAnimation); renderer.addClass(elementRef.nativeElement, 'ant-calendar-picker'); } diff --git a/components/divider/demo/horizontal.ts b/components/divider/demo/horizontal.ts index 3531deb9fa7..e1c96d04d65 100644 --- a/components/divider/demo/horizontal.ts +++ b/components/divider/demo/horizontal.ts @@ -4,19 +4,28 @@ import { Component } from '@angular/core'; selector: 'nz-demo-divider-horizontal', template: `
-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

Add -

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

` }) - -export class NzDemoDividerHorizontalComponent { - -} +export class NzDemoDividerHorizontalComponent {} diff --git a/components/divider/demo/orientation.ts b/components/divider/demo/orientation.ts index 7e4d40501fb..d2995339d41 100644 --- a/components/divider/demo/orientation.ts +++ b/components/divider/demo/orientation.ts @@ -5,13 +5,16 @@ import { Component } from '@angular/core'; template: `
-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae sunt a te dicta? Refert tamen, quo modo.

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista probare, quae + sunt a te dicta? Refert tamen, quo modo. +

` }) - -export class NzDemoDividerOrientationComponent { - -} +export class NzDemoDividerOrientationComponent {} diff --git a/components/divider/demo/vertical.ts b/components/divider/demo/vertical.ts index 2e67725fd51..ec3589f6bd8 100644 --- a/components/divider/demo/vertical.ts +++ b/components/divider/demo/vertical.ts @@ -3,7 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-divider-vertical', template: ` -
Text +
+ Text Link @@ -11,7 +12,4 @@ import { Component } from '@angular/core';
` }) - -export class NzDemoDividerVerticalComponent { - -} +export class NzDemoDividerVerticalComponent {} diff --git a/components/divider/divider.spec.ts b/components/divider/divider.spec.ts index 90d8079d38e..5a3ee8f4a9c 100644 --- a/components/divider/divider.spec.ts +++ b/components/divider/divider.spec.ts @@ -13,8 +13,8 @@ describe('divider', () => { let dl: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ - imports: [ NzDividerModule, NzIconTestModule ], - declarations: [ TestDividerComponent, TestDividerTextTemplateComponent ] + imports: [NzDividerModule, NzIconTestModule], + declarations: [TestDividerComponent, TestDividerTextTemplateComponent] }).compileComponents(); fixture = TestBed.createComponent(TestDividerComponent); context = fixture.componentInstance; @@ -23,7 +23,7 @@ describe('divider', () => { }); describe('#nzDashed', () => { - for (const value of [ true, false ]) { + for (const value of [true, false]) { it(`[${value}]`, () => { context.nzDashed = value; fixture.detectChanges(); @@ -33,7 +33,7 @@ describe('divider', () => { }); describe('#nzType', () => { - for (const value of [ 'horizontal', 'vertical' ]) { + for (const value of ['horizontal', 'vertical']) { it(`[${value}]`, () => { context.nzType = value; fixture.detectChanges(); @@ -43,7 +43,7 @@ describe('divider', () => { }); describe('#nzText', () => { - for (const item of [ { text: 'with text', ret: true }, { text: undefined, ret: false } ]) { + for (const item of [{ text: 'with text', ret: true }, { text: undefined, ret: false }]) { it(`[${item.text}]`, () => { context.nzText = item.text; fixture.detectChanges(); @@ -60,7 +60,7 @@ describe('divider', () => { }); describe('#nzOrientation', () => { - [ 'left', 'right' ].forEach(type => { + ['left', 'right'].forEach(type => { it(`with ${type}`, () => { context.nzOrientation = type; fixture.detectChanges(); @@ -72,11 +72,13 @@ describe('divider', () => { @Component({ template: ` - + ` }) class TestDividerComponent { @@ -89,10 +91,9 @@ class TestDividerComponent { @Component({ template: ` - - Add - + + Add + ` }) -class TestDividerTextTemplateComponent { -} +class TestDividerTextTemplateComponent {} diff --git a/components/divider/nz-divider.component.ts b/components/divider/nz-divider.component.ts index 2c4587ec9b1..182ab4c54e5 100644 --- a/components/divider/nz-divider.component.ts +++ b/components/divider/nz-divider.component.ts @@ -13,12 +13,12 @@ import { NzUpdateHostClassService } from '../core/services/update-host-class.ser import { InputBoolean } from '../core/util'; @Component({ - selector : 'nz-divider', - templateUrl : './nz-divider.component.html', + selector: 'nz-divider', + templateUrl: './nz-divider.component.html', preserveWhitespaces: false, - providers : [ NzUpdateHostClassService ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + providers: [NzUpdateHostClassService], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzDividerComponent implements OnChanges, OnInit { @Input() nzText: string | TemplateRef; @@ -27,17 +27,16 @@ export class NzDividerComponent implements OnChanges, OnInit { @Input() @InputBoolean() nzDashed = false; private setClass(): void { - const orientationPrefix = (this.nzOrientation.length > 0) ? '-' + this.nzOrientation : this.nzOrientation; + const orientationPrefix = this.nzOrientation.length > 0 ? '-' + this.nzOrientation : this.nzOrientation; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ 'ant-divider' ] : true, - [ `ant-divider-${this.nzType}` ] : true, - [ `ant-divider-with-text${orientationPrefix}` ]: this.nzText, - [ `ant-divider-dashed` ] : this.nzDashed + ['ant-divider']: true, + [`ant-divider-${this.nzType}`]: true, + [`ant-divider-with-text${orientationPrefix}`]: this.nzText, + [`ant-divider-dashed`]: this.nzDashed }); } - constructor(private elementRef: ElementRef, private nzUpdateHostClassService: NzUpdateHostClassService) { - } + constructor(private elementRef: ElementRef, private nzUpdateHostClassService: NzUpdateHostClassService) {} ngOnChanges(): void { this.setClass(); diff --git a/components/divider/nz-divider.module.ts b/components/divider/nz-divider.module.ts index d08936d7976..4464a9af825 100644 --- a/components/divider/nz-divider.module.ts +++ b/components/divider/nz-divider.module.ts @@ -4,9 +4,8 @@ import { NzAddOnModule } from '../core/addon/addon.module'; import { NzDividerComponent } from './nz-divider.component'; @NgModule({ - imports : [ CommonModule, NzAddOnModule ], - declarations: [ NzDividerComponent ], - exports : [ NzDividerComponent ] + imports: [CommonModule, NzAddOnModule], + declarations: [NzDividerComponent], + exports: [NzDividerComponent] }) -export class NzDividerModule { -} +export class NzDividerModule {} diff --git a/components/drawer/demo/basic-right.ts b/components/drawer/demo/basic-right.ts index 99331435877..84749286cf1 100755 --- a/components/drawer/demo/basic-right.ts +++ b/components/drawer/demo/basic-right.ts @@ -4,14 +4,19 @@ import { Component } from '@angular/core'; selector: 'nz-demo-drawer-basic-right', template: ` - +

Some contents...

Some contents...

Some contents...

` }) - export class NzDemoDrawerBasicRightComponent { visible = false; diff --git a/components/drawer/demo/from-drawer.ts b/components/drawer/demo/from-drawer.ts index ebb101f36f5..f29d15825fe 100755 --- a/components/drawer/demo/from-drawer.ts +++ b/components/drawer/demo/from-drawer.ts @@ -4,14 +4,21 @@ import { Component } from '@angular/core'; selector: 'nz-demo-drawer-from-drawer', template: ` - +
Name - +
@@ -20,7 +27,7 @@ import { Component } from '@angular/core'; Url - + @@ -67,7 +74,11 @@ import { Component } from '@angular/core'; Description - +
@@ -79,20 +90,21 @@ import { Component } from '@angular/core';
`, - styles: [` - .footer { - position: absolute; - bottom: 0px; - width: 100%; - border-top: 1px solid rgb(232, 232, 232); - padding: 10px 16px; - text-align: right; - left: 0px; - background: #fff; - } - `] + styles: [ + ` + .footer { + position: absolute; + bottom: 0px; + width: 100%; + border-top: 1px solid rgb(232, 232, 232); + padding: 10px 16px; + text-align: right; + left: 0px; + background: #fff; + } + ` + ] }) - export class NzDemoDrawerFromDrawerComponent { visible = false; diff --git a/components/drawer/demo/multi-level-drawer.ts b/components/drawer/demo/multi-level-drawer.ts index 099e39aca9b..d252c2849af 100755 --- a/components/drawer/demo/multi-level-drawer.ts +++ b/components/drawer/demo/multi-level-drawer.ts @@ -4,14 +4,21 @@ import { Component } from '@angular/core'; selector: 'nz-demo-drawer-multi-level-drawer', template: ` - +
Name - +
@@ -42,20 +49,21 @@ import { Component } from '@angular/core'; `, - styles: [` - .footer { - position: absolute; - bottom: 0px; - width: 100%; - border-top: 1px solid rgb(232, 232, 232); - padding: 10px 16px; - text-align: right; - left: 0px; - background: #fff; - } - `] + styles: [ + ` + .footer { + position: absolute; + bottom: 0px; + width: 100%; + border-top: 1px solid rgb(232, 232, 232); + padding: 10px 16px; + text-align: right; + left: 0px; + background: #fff; + } + ` + ] }) - export class NzDemoDrawerMultiLevelDrawerComponent { visible = false; childrenVisible = false; diff --git a/components/drawer/demo/placement.ts b/components/drawer/demo/placement.ts index e096385d256..027c38aed2a 100755 --- a/components/drawer/demo/placement.ts +++ b/components/drawer/demo/placement.ts @@ -10,16 +10,20 @@ import { Component } from '@angular/core'; - +

Some contents...

Some contents...

Some contents...

` }) - export class NzDemoDrawerPlacementComponent { - visible = false; placement = 'left'; open(): void { diff --git a/components/drawer/demo/service.ts b/components/drawer/demo/service.ts index 3a54f3e86f4..7ebd4e7bec1 100644 --- a/components/drawer/demo/service.ts +++ b/components/drawer/demo/service.ts @@ -7,29 +7,27 @@ import { NzDrawerRef, NzDrawerService } from 'ng-zorro-antd'; selector: 'nz-demo-drawer-service', template: ` - value: {{data?.value}} -
+ value: {{ data?.value }} +
- +
  ` }) - export class NzDemoDrawerServiceComponent { - @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{ $implicit: { value: string; }; drawerRef: NzDrawerRef; }> ; + @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{ + $implicit: { value: string }; + drawerRef: NzDrawerRef; + }>; value = 'ng'; - constructor( - private drawerService: NzDrawerService - ) { - - } + constructor(private drawerService: NzDrawerService) {} openTemplate(): void { const drawerRef = this.drawerService.create({ @@ -69,27 +67,22 @@ export class NzDemoDrawerServiceComponent { } }); } - } @Component({ selector: 'nz-drawer-custom-component', template: `
- +
` }) export class NzDrawerCustomComponent { - @Input() value = ''; - constructor( - private drawerRef: NzDrawerRef - ) { - } + constructor(private drawerRef: NzDrawerRef) {} close(): void { this.drawerRef.close(this.value); diff --git a/components/drawer/demo/user-profile.ts b/components/drawer/demo/user-profile.ts index 7297dd0e6c2..1b468ec2ccc 100755 --- a/components/drawer/demo/user-profile.ts +++ b/components/drawer/demo/user-profile.ts @@ -12,9 +12,10 @@ import { Component } from '@angular/core'; + nzDescription="Progresser AFX" + > - {{item.name}} + {{ item.name }} @@ -26,43 +27,50 @@ import { Component } from '@angular/core';
-

Full Name:

Lily +

Full Name:

+ Lily
-

Account:

AntDesign@example.com +

Account:

+ AntDesign@example.com
-

City:

HangZhou +

City:

+ HangZhou
-

Country:

China🇨🇳 +

Country:

+ China🇨🇳
-

Birthday:

February 2,1900 +

Birthday:

+ February 2,1900
-

Website:

- +

Website:

+ -
-

Message:

Make things as simple as possible but no simpler. +

Message:

+ Make things as simple as possible but no simpler.
@@ -71,19 +79,22 @@ import { Component } from '@angular/core';
-

Position:

Programmer +

Position:

+ Programmer
-

Responsibilities:

Coding +

Responsibilities:

+ Coding
-

Department:

AFX +

Department:

+ AFX
@@ -96,7 +107,10 @@ import { Component } from '@angular/core';
-

Skills:

C / C + +, data structures, software engineering, operating systems, computer networks, databases, compiler theory, computer architecture, Microcomputer Principle and Interface Technology, Computer English, Java, ASP, etc. +

Skills:

+ C / C + +, data structures, software engineering, operating systems, computer networks, databases, compiler + theory, computer architecture, Microcomputer Principle and Interface Technology, Computer English, Java, + ASP, etc.
@@ -105,12 +119,14 @@ import { Component } from '@angular/core';
-

Email:

AntDesign@example.com +

Email:

+ AntDesign@example.com
-

Phone Number:

+86 181 0000 0000 +

Phone Number:

+ +86 181 0000 0000
@@ -126,30 +142,28 @@ import { Component } from '@angular/core'; `, styles: [ ` - .title { - font-size: 16px; - color: rgba(0, 0, 0, 0.85); - line-height: 24px; - display: block; - margin-bottom: 16px; - } - .item-wrap { - font-size: 14px; - line-height: 22px; - margin-bottom: 7px; - color: rgba(0, 0, 0, 0.65); - } - .label { - margin-right: 8px; - display: inline-block; - color: rgba(0, 0, 0, 0.85); - } + .title { + font-size: 16px; + color: rgba(0, 0, 0, 0.85); + line-height: 24px; + display: block; + margin-bottom: 16px; + } + .item-wrap { + font-size: 14px; + line-height: 22px; + margin-bottom: 7px; + color: rgba(0, 0, 0, 0.65); + } + .label { + margin-right: 8px; + display: inline-block; + color: rgba(0, 0, 0, 0.85); + } ` ] }) - export class NzDemoDrawerUserProfileComponent { - data = [ { name: 'Lily' diff --git a/components/drawer/nz-drawer-options.ts b/components/drawer/nz-drawer-options.ts index f007fe1e0cd..54be7e59a82 100644 --- a/components/drawer/nz-drawer-options.ts +++ b/components/drawer/nz-drawer-options.ts @@ -10,7 +10,7 @@ export interface NzDrawerOptions { nzMask?: boolean; nzNoAnimation?: boolean; nzTitle?: string | TemplateRef<{}>; - nzContent?: TemplateRef<{ $implicit: D, drawerRef: NzDrawerRef }> | Type; + nzContent?: TemplateRef<{ $implicit: D; drawerRef: NzDrawerRef }> | Type; nzContentParams?: D; nzMaskStyle?: object; nzBodyStyle?: object; diff --git a/components/drawer/nz-drawer-ref.ts b/components/drawer/nz-drawer-ref.ts index 722698142a2..9227f9b7368 100644 --- a/components/drawer/nz-drawer-ref.ts +++ b/components/drawer/nz-drawer-ref.ts @@ -4,7 +4,6 @@ import { NzDrawerPlacement } from './nz-drawer-options'; // tslint:disable-next-line:no-any export abstract class NzDrawerRef { - abstract afterClose: Observable; abstract afterOpen: Observable; abstract close(result?: R): void; diff --git a/components/drawer/nz-drawer.component.ts b/components/drawer/nz-drawer.component.ts index 006cd4c5942..865478f8526 100644 --- a/components/drawer/nz-drawer.component.ts +++ b/components/drawer/nz-drawer.component.ts @@ -34,14 +34,15 @@ import { NzDrawerRef } from './nz-drawer-ref'; export const DRAWER_ANIMATE_DURATION = 300; @Component({ - selector : 'nz-drawer', - templateUrl : './nz-drawer.component.html', + selector: 'nz-drawer', + templateUrl: './nz-drawer.component.html', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush + changeDetection: ChangeDetectionStrategy.OnPush }) // tslint:disable-next-line:no-any -export class NzDrawerComponent extends NzDrawerRef implements OnInit, OnDestroy, AfterViewInit, OnChanges, NzDrawerOptions { - @Input() nzContent: TemplateRef<{ $implicit: D, drawerRef: NzDrawerRef }> | Type; +export class NzDrawerComponent extends NzDrawerRef + implements OnInit, OnDestroy, AfterViewInit, OnChanges, NzDrawerOptions { + @Input() nzContent: TemplateRef<{ $implicit: D; drawerRef: NzDrawerRef }> | Type; @Input() @InputBoolean() nzClosable = true; @Input() @InputBoolean() nzMaskClosable = true; @Input() @InputBoolean() nzMask = true; @@ -85,7 +86,7 @@ export class NzDrawerComponent extends NzDrawerRef }; get offsetTransform(): string | null { - if (!this.isOpen || (this.nzOffsetX + this.nzOffsetY) === 0) { + if (!this.isOpen || this.nzOffsetX + this.nzOffsetY === 0) { return null; } switch (this.nzPlacement) { @@ -101,7 +102,6 @@ export class NzDrawerComponent extends NzDrawerRef } get transform(): string | null { - if (this.isOpen) { return null; } @@ -153,7 +153,8 @@ export class NzDrawerComponent extends NzDrawerRef private injector: Injector, private changeDetectorRef: ChangeDetectorRef, private focusTrapFactory: FocusTrapFactory, - private viewContainerRef: ViewContainerRef) { + private viewContainerRef: ViewContainerRef + ) { super(); } @@ -235,7 +236,7 @@ export class NzDrawerComponent extends NzDrawerRef this.bodyPortalOutlet.dispose(); if (this.nzContent instanceof Type) { - const childInjector = new PortalInjector(this.injector, new WeakMap([ [ NzDrawerRef, this ] ])); + const childInjector = new PortalInjector(this.injector, new WeakMap([[NzDrawerRef, this]])); const componentPortal = new ComponentPortal(this.nzContent, null, childInjector); const componentRef = this.bodyPortalOutlet.attachComponentPortal(componentPortal); Object.assign(componentRef.instance, this.nzContentParams); diff --git a/components/drawer/nz-drawer.module.ts b/components/drawer/nz-drawer.module.ts index 45a8d89d0eb..844ab0082df 100644 --- a/components/drawer/nz-drawer.module.ts +++ b/components/drawer/nz-drawer.module.ts @@ -11,11 +11,10 @@ import { NzDrawerComponent } from './nz-drawer.component'; import { NzDrawerService } from './nz-drawer.service'; @NgModule({ - imports : [ CommonModule, OverlayModule, PortalModule, NzIconModule, NzAddOnModule, NzNoAnimationModule ], - exports : [ NzDrawerComponent ], - declarations : [ NzDrawerComponent ], - entryComponents: [ NzDrawerComponent ], - providers : [ NzDrawerService ] + imports: [CommonModule, OverlayModule, PortalModule, NzIconModule, NzAddOnModule, NzNoAnimationModule], + exports: [NzDrawerComponent], + declarations: [NzDrawerComponent], + entryComponents: [NzDrawerComponent], + providers: [NzDrawerService] }) -export class NzDrawerModule { -} +export class NzDrawerModule {} diff --git a/components/drawer/nz-drawer.service.ts b/components/drawer/nz-drawer.service.ts index 4b345c7d815..008958b410f 100644 --- a/components/drawer/nz-drawer.service.ts +++ b/components/drawer/nz-drawer.service.ts @@ -17,20 +17,15 @@ export class DrawerBuilderForService { this.updateOptions(this.options); // Prevent repeatedly open drawer when tap focus element. this.drawerRef!.instance.savePreviouslyFocusedElement(); - this.drawerRef!.instance.nzOnViewInit - .pipe(takeUntil(this.unsubscribe$)) - .subscribe(() => { + this.drawerRef!.instance.nzOnViewInit.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.drawerRef!.instance.open(); }); - this.drawerRef!.instance.nzOnClose - .subscribe(() => { + this.drawerRef!.instance.nzOnClose.subscribe(() => { this.drawerRef!.instance.close(); }); - this.drawerRef!.instance.afterClose - .pipe(takeUntil(this.unsubscribe$)) - .subscribe(() => { + this.drawerRef!.instance.afterClose.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.overlayRef.dispose(); this.drawerRef = null; this.unsubscribe$.next(); @@ -52,11 +47,9 @@ export class DrawerBuilderForService { } } -@Injectable({ providedIn: 'root'}) +@Injectable({ providedIn: 'root' }) export class NzDrawerService { - - constructor(private overlay: Overlay) { - } + constructor(private overlay: Overlay) {} // tslint:disable-next-line:no-any create(options: NzDrawerOptions): NzDrawerRef { diff --git a/components/drawer/nz-drawer.spec.ts b/components/drawer/nz-drawer.spec.ts index af33ab27e74..285fcd71f23 100644 --- a/components/drawer/nz-drawer.spec.ts +++ b/components/drawer/nz-drawer.spec.ts @@ -19,10 +19,9 @@ describe('NzDrawerComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzDrawerModule, NoopAnimationsModule ], - declarations: [ NzTestDrawerComponent ] - }) - .compileComponents(); + imports: [NzDrawerModule, NoopAnimationsModule], + declarations: [NzTestDrawerComponent] + }).compileComponents(); })); beforeEach(() => { @@ -31,7 +30,7 @@ describe('NzDrawerComponent', () => { fixture.detectChanges(); }); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); forceScrollElement = document.createElement('div'); @@ -88,7 +87,6 @@ describe('NzDrawerComponent', () => { fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); expect(overlayContainerElement.querySelector('.ant-drawer .ant-drawer-close')).toBe(null); - }); it('should closable', () => { @@ -135,8 +133,12 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-mask') as HTMLElement).style.color).toBe('gray'); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-body') as HTMLElement).style.color).toBe('gray'); + expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-mask') as HTMLElement).style.color).toBe( + 'gray' + ); + expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-body') as HTMLElement).style.color).toBe( + 'gray' + ); }); it('should not render title', () => { @@ -151,7 +153,9 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-title') as HTMLElement).innerText.trim()).toBe('test'); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-title') as HTMLElement).innerText.trim() + ).toBe('test'); }); it('should support TemplateRef title', () => { @@ -167,7 +171,10 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content') as HTMLElement).getBoundingClientRect().width).toBe(500); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content') as HTMLElement).getBoundingClientRect() + .width + ).toBe(500); }); it('should support custom number type width', () => { @@ -175,7 +182,10 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content') as HTMLElement).getBoundingClientRect().width).toBe(520); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content') as HTMLElement).getBoundingClientRect() + .width + ).toBe(520); }); it('should support custom height', () => { @@ -184,7 +194,11 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content-wrapper') as HTMLElement).getBoundingClientRect().height).toBe(500); + expect( + (overlayContainerElement.querySelector( + '.ant-drawer .ant-drawer-content-wrapper' + ) as HTMLElement).getBoundingClientRect().height + ).toBe(500); component.placement = 'left'; fixture.detectChanges(); }); @@ -195,7 +209,11 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content-wrapper') as HTMLElement).getBoundingClientRect().height).toBe(520); + expect( + (overlayContainerElement.querySelector( + '.ant-drawer .ant-drawer-content-wrapper' + ) as HTMLElement).getBoundingClientRect().height + ).toBe(520); component.placement = 'left'; fixture.detectChanges(); }); @@ -204,60 +222,106 @@ describe('NzDrawerComponent', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content-wrapper') as HTMLElement).classList.contains('test-class')).toBe(true); + expect( + (overlayContainerElement.querySelector( + '.ant-drawer .ant-drawer-content-wrapper' + ) as HTMLElement).classList.contains('test-class') + ).toBe(true); }); it('should nzZIndex work', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-mask') as HTMLElement).style.zIndex).toBe('1001'); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content-wrapper') as HTMLElement).style.zIndex).toBe('1001'); + expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-mask') as HTMLElement).style.zIndex).toBe( + '1001' + ); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-content-wrapper') as HTMLElement).style.zIndex + ).toBe('1001'); }); it('should nzPlacement work', () => { component.open(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top')).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left') + ).toBe(true); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top') + ).toBe(false); component.placement = 'right'; fixture.detectChanges(); component.close(); fixture.detectChanges(); component.open(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top')).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right') + ).toBe(true); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top') + ).toBe(false); component.placement = 'top'; fixture.detectChanges(); component.close(); fixture.detectChanges(); component.open(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top')).toBe(true); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top') + ).toBe(true); component.placement = 'bottom'; fixture.detectChanges(); component.close(); fixture.detectChanges(); component.open(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top')).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom') + ).toBe(true); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top') + ).toBe(false); component.close(); fixture.detectChanges(); component.placement = 'Invalid'; fixture.detectChanges(); component.open(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom')).toBe(false); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top')).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-left') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-right') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-bottom') + ).toBe(false); + expect( + (overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).classList.contains('ant-drawer-top') + ).toBe(false); component.close(); fixture.detectChanges(); }); @@ -269,12 +333,16 @@ describe('NzDrawerComponent', () => { component.offsetX = 100; fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe('translateX(100px)'); + expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe( + 'translateX(100px)' + ); fixture.detectChanges(); component.placement = 'right'; component.offsetX = 100; fixture.detectChanges(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe('translateX(-100px)'); + expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe( + 'translateX(-100px)' + ); component.close(); fixture.detectChanges(); }); @@ -286,12 +354,16 @@ describe('NzDrawerComponent', () => { component.offsetY = 100; fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-drawer')!.classList.contains('ant-drawer-open')).toBe(true); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe('translateY(100px)'); + expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe( + 'translateY(100px)' + ); fixture.detectChanges(); component.placement = 'bottom'; component.offsetY = 100; fixture.detectChanges(); - expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe('translateY(-100px)'); + expect((overlayContainerElement.querySelector('.ant-drawer') as HTMLElement).style.transform).toBe( + 'translateY(-100px)' + ); component.close(); fixture.detectChanges(); }); @@ -300,8 +372,12 @@ describe('NzDrawerComponent', () => { component.placement = 'right'; component.open(); fixture.detectChanges(); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-wrapper-body') as HTMLElement).style.overflow).toBe('auto'); - expect((overlayContainerElement.querySelector('.ant-drawer .ant-drawer-wrapper-body') as HTMLElement).style.height).toBe('100%'); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-wrapper-body') as HTMLElement).style.overflow + ).toBe('auto'); + expect( + (overlayContainerElement.querySelector('.ant-drawer .ant-drawer-wrapper-body') as HTMLElement).style.height + ).toBe('100%'); }); }); @@ -314,12 +390,12 @@ describe('NzDrawerService', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzDrawerModule ], - providers : [NzDrawerService], - declarations: [ NzTestDrawerWithServiceComponent, NzDrawerCustomComponent ] + imports: [NzDrawerModule], + providers: [NzDrawerService], + declarations: [NzTestDrawerWithServiceComponent, NzDrawerCustomComponent] }); TestBed.overrideModule(BrowserDynamicTestingModule, { - set: { entryComponents: [ NzDrawerCustomComponent ] } + set: { entryComponents: [NzDrawerCustomComponent] } }).compileComponents(); })); @@ -329,7 +405,7 @@ describe('NzDrawerService', () => { fixture.detectChanges(); })); - beforeEach(inject([ OverlayContainer, NzDrawerService ], (oc: OverlayContainer, ds: NzDrawerService) => { + beforeEach(inject([OverlayContainer, NzDrawerService], (oc: OverlayContainer, ds: NzDrawerService) => { overlayContainer = oc; drawerService = ds; overlayContainerElement = oc.getContainerElement(); @@ -355,8 +431,8 @@ describe('NzDrawerService', () => { const openSpy = jasmine.createSpy('afterOpen spy'); const closeSpy = jasmine.createSpy('afterClose spy').and.returnValue(1); const drawerRef = drawerService.create({ - nzTitle : 'Service', - nzContent : NzDrawerCustomComponent, + nzTitle: 'Service', + nzContent: NzDrawerCustomComponent, nzContentParams: { value: 1 } }); drawerRef.afterOpen.subscribe(openSpy); @@ -370,7 +446,6 @@ describe('NzDrawerService', () => { tick(300); expect(closeSpy).toHaveBeenCalled(); })); - }); @Component({ @@ -396,13 +471,14 @@ describe('NzDrawerService', () => { [nzTitle]="title" [nzOffsetX]="offsetX" [nzOffsetY]="offsetY" - (nzOnClose)="close()"> + (nzOnClose)="close()" + >

Some contents...

Some contents...

Some contents...

`, - styles : [] + styles: [] }) class NzTestDrawerComponent { visible = false; @@ -438,7 +514,7 @@ class NzTestDrawerComponent { ` }) class NzTestDrawerWithServiceComponent { - @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{ $implicit: number, drawerRef: NzDrawerRef}>; + @ViewChild('drawerTemplate') drawerTemplate: TemplateRef<{ $implicit: number; drawerRef: NzDrawerRef }>; templateOpenSpy = jasmine.createSpy('template afterOpen spy'); templateCloseSpy = jasmine.createSpy('template afterClose spy'); templateDrawerRef: NzDrawerRef; @@ -447,8 +523,8 @@ class NzTestDrawerWithServiceComponent { openTemplate(): void { this.templateDrawerRef = this.drawerService.create({ - nzTitle : 'Service', - nzContent : this.drawerTemplate + nzTitle: 'Service', + nzContent: this.drawerTemplate }); this.templateDrawerRef.afterOpen.subscribe(this.templateOpenSpy); diff --git a/components/dropdown/demo/basic.ts b/components/dropdown/demo/basic.ts index d48212fd6d3..322529e95ec 100644 --- a/components/dropdown/demo/basic.ts +++ b/components/dropdown/demo/basic.ts @@ -4,9 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-basic', template: ` - - Hover me - + Hover me - `, - styles : [] + + `, + styles: [] }) -export class NzDemoDropdownBasicComponent { -} +export class NzDemoDropdownBasicComponent {} diff --git a/components/dropdown/demo/context-menu.ts b/components/dropdown/demo/context-menu.ts index fe9f7b44af8..969dc90b78d 100644 --- a/components/dropdown/demo/context-menu.ts +++ b/components/dropdown/demo/context-menu.ts @@ -4,7 +4,10 @@ import { NzDropdownContextComponent, NzDropdownService, NzMenuItemDirective } fr @Component({ selector: 'nz-demo-dropdown-context-menu', template: ` -
+
  • 1st menu item
  • @@ -29,7 +32,7 @@ import { NzDropdownContextComponent, NzDropdownService, NzMenuItemDirective } fr Context Menu
`, - styles : [] + styles: [] }) export class NzDemoDropdownContextMenuComponent { private dropdown: NzDropdownContextComponent; @@ -43,7 +46,5 @@ export class NzDemoDropdownContextMenuComponent { this.dropdown.close(); } - constructor(private nzDropdownService: NzDropdownService) { - - } + constructor(private nzDropdownService: NzDropdownService) {} } diff --git a/components/dropdown/demo/dropdown-button.ts b/components/dropdown/demo/dropdown-button.ts index 05c0c7a5582..62c810023a9 100644 --- a/components/dropdown/demo/dropdown-button.ts +++ b/components/dropdown/demo/dropdown-button.ts @@ -48,8 +48,8 @@ import { Component } from '@angular/core';
`, - styles : [ - ` + styles: [ + ` nz-dropdown-button { margin-right: 8px; } diff --git a/components/dropdown/demo/event.ts b/components/dropdown/demo/event.ts index 7749ab231f1..45e3d616091 100644 --- a/components/dropdown/demo/event.ts +++ b/components/dropdown/demo/event.ts @@ -4,16 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-event', template: ` - - Hover me, Click menu item - + Hover me, Click menu item
  • 1st menu item
  • 2nd menu item
  • 3rd menu item
-
`, - styles : [] + + `, + styles: [] }) export class NzDemoDropdownEventComponent { log(data: string): void { diff --git a/components/dropdown/demo/item.ts b/components/dropdown/demo/item.ts index 48e95f83489..8708cd1d23a 100644 --- a/components/dropdown/demo/item.ts +++ b/components/dropdown/demo/item.ts @@ -4,9 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-item', template: ` - - Hover me - + Hover me
  • 1st menu item @@ -17,8 +15,8 @@ import { Component } from '@angular/core';
  • 3rd menu item(disabled)
-
`, - styles : [] + + `, + styles: [] }) -export class NzDemoDropdownItemComponent { -} +export class NzDemoDropdownItemComponent {} diff --git a/components/dropdown/demo/overlay-visible.ts b/components/dropdown/demo/overlay-visible.ts index f4329dc801e..5090c0d9cf4 100644 --- a/components/dropdown/demo/overlay-visible.ts +++ b/components/dropdown/demo/overlay-visible.ts @@ -4,16 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-overlay-visible', template: ` - - Hover me - + Hover me
  • Clicking me will not close the menu.
  • Clicking me will not close the menu also.
  • Clicking me will close the menu
-
`, - styles : [] + + `, + styles: [] }) export class NzDemoDropdownOverlayVisibleComponent { visible = false; diff --git a/components/dropdown/demo/placement.ts b/components/dropdown/demo/placement.ts index 7d0ff6adf43..1fb59fc7254 100644 --- a/components/dropdown/demo/placement.ts +++ b/components/dropdown/demo/placement.ts @@ -88,9 +88,10 @@ import { Component } from '@angular/core'; -
`, - styles : [ - ` +
+ `, + styles: [ + ` [nz-button] { margin-right: 8px; margin-bottom: 8px; @@ -98,5 +99,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoDropdownPlacementComponent { -} +export class NzDemoDropdownPlacementComponent {} diff --git a/components/dropdown/demo/sub-menu.ts b/components/dropdown/demo/sub-menu.ts index 3d241056e3c..718692ab210 100644 --- a/components/dropdown/demo/sub-menu.ts +++ b/components/dropdown/demo/sub-menu.ts @@ -4,9 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-sub-menu', template: ` - - Cascading menu - + Cascading menu
  • 1st menu item
  • 2nd menu item
  • @@ -25,8 +23,9 @@ import { Component } from '@angular/core';
-
`, - styles : [] + + `, + styles: [] }) export class NzDemoDropdownSubMenuComponent { change(value: boolean): void { diff --git a/components/dropdown/demo/trigger.ts b/components/dropdown/demo/trigger.ts index b90b96c9bc2..b9af1fc796c 100644 --- a/components/dropdown/demo/trigger.ts +++ b/components/dropdown/demo/trigger.ts @@ -4,9 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-dropdown-trigger', template: ` - - Click me - + Click me
  • 1st menu item
  • 2nd menu item
  • @@ -27,8 +25,8 @@ import { Component } from '@angular/core';
-
`, - styles : [] + + `, + styles: [] }) -export class NzDemoDropdownTriggerComponent { -} +export class NzDemoDropdownTriggerComponent {} diff --git a/components/dropdown/nz-dropdown-button.component.ts b/components/dropdown/nz-dropdown-button.component.ts index 54f30d2786f..381af5485fb 100644 --- a/components/dropdown/nz-dropdown-button.component.ts +++ b/components/dropdown/nz-dropdown-button.component.ts @@ -3,10 +3,12 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, - EventEmitter, Host, + EventEmitter, + Host, Input, OnChanges, - OnDestroy, Optional, + OnDestroy, + Optional, Output, ViewChild, ViewEncapsulation @@ -19,38 +21,42 @@ import { NzDropDownDirective } from './nz-dropdown.directive'; import { NzMenuDropdownService } from './nz-menu-dropdown.service'; @Component({ - selector : 'nz-dropdown-button', + selector: 'nz-dropdown-button', preserveWhitespaces: false, - animations : [ slideMotion ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ NzMenuDropdownService ], - templateUrl : './nz-dropdown-button.component.html', - styles : [ ` - nz-dropdown-button { - position: relative; - display: inline-block; - } + animations: [slideMotion], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [NzMenuDropdownService], + templateUrl: './nz-dropdown-button.component.html', + styles: [ + ` + nz-dropdown-button { + position: relative; + display: inline-block; + } - .ant-dropdown { - top: 100%; - left: 0; - position: relative; - width: 100%; - margin-top: 4px; - margin-bottom: 4px; - } - ` ] + .ant-dropdown { + top: 100%; + left: 0; + position: relative; + width: 100%; + margin-top: 4px; + margin-bottom: 4px; + } + ` + ] }) - export class NzDropDownButtonComponent extends NzDropDownComponent implements OnDestroy, AfterContentInit, OnChanges { @Input() nzSize = 'default'; @Input() nzType = 'default'; @Output() readonly nzClick = new EventEmitter(); @ViewChild(NzDropDownDirective) nzDropDownDirective: NzDropDownDirective; - constructor(cdr: ChangeDetectorRef, nzMenuDropdownService: NzMenuDropdownService, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + cdr: ChangeDetectorRef, + nzMenuDropdownService: NzMenuDropdownService, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { super(cdr, nzMenuDropdownService, noAnimation); } diff --git a/components/dropdown/nz-dropdown-context.component.ts b/components/dropdown/nz-dropdown-context.component.ts index e15d4970a65..938516c8c7e 100644 --- a/components/dropdown/nz-dropdown-context.component.ts +++ b/components/dropdown/nz-dropdown-context.component.ts @@ -14,15 +14,15 @@ import { NzDropdownService } from './nz-dropdown.service'; import { NzMenuDropdownService } from './nz-menu-dropdown.service'; @Component({ - selector : 'nz-dropdown-context', - animations : [ slideMotion ], + selector: 'nz-dropdown-context', + animations: [slideMotion], preserveWhitespaces: false, - templateUrl : './nz-dropdown-context.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ NzMenuDropdownService ], - styles : [ - ` + templateUrl: './nz-dropdown-context.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [NzMenuDropdownService], + styles: [ + ` nz-dropdown-context { display: block; } @@ -45,13 +45,16 @@ export class NzDropdownContextComponent implements OnDestroy { private control: NzDropdownService; private destroy$ = new Subject(); - init(open: boolean, templateRef: TemplateRef, positionChanges: Observable, control: NzDropdownService): void { + init( + open: boolean, + templateRef: TemplateRef, + positionChanges: Observable, + control: NzDropdownService + ): void { this.open = open; this.templateRef = templateRef; this.control = control; - positionChanges.pipe( - takeUntil(this.destroy$) - ).subscribe(data => { + positionChanges.pipe(takeUntil(this.destroy$)).subscribe(data => { this.dropDownPosition = data.connectionPair.overlayY === 'bottom' ? 'top' : 'bottom'; this.cdr.markForCheck(); }); @@ -68,8 +71,7 @@ export class NzDropdownContextComponent implements OnDestroy { } } - constructor(private cdr: ChangeDetectorRef) { - } + constructor(private cdr: ChangeDetectorRef) {} // TODO auto set dropdown class after the bug resolved /** https://github.com/angular/angular/issues/14842 **/ diff --git a/components/dropdown/nz-dropdown.component.ts b/components/dropdown/nz-dropdown.component.ts index 9e86c6e1d6a..4c1e3276835 100644 --- a/components/dropdown/nz-dropdown.component.ts +++ b/components/dropdown/nz-dropdown.component.ts @@ -5,10 +5,12 @@ import { ChangeDetectorRef, Component, ContentChild, - EventEmitter, Host, + EventEmitter, + Host, Input, OnChanges, - OnDestroy, Optional, + OnDestroy, + Optional, Output, SimpleChanges, ViewChild, @@ -27,15 +29,15 @@ import { NzMenuDropdownService } from './nz-menu-dropdown.service'; export type NzPlacement = 'bottomLeft' | 'bottomCenter' | 'bottomRight' | 'topLeft' | 'topCenter' | 'topRight'; @Component({ - selector : 'nz-dropdown', + selector: 'nz-dropdown', preserveWhitespaces: false, - providers : [ NzMenuDropdownService ], - animations : [ slideMotion ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-dropdown.component.html', - styles : [ - ` + providers: [NzMenuDropdownService], + animations: [slideMotion], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-dropdown.component.html', + styles: [ + ` .ant-dropdown { top: 100%; left: 0; @@ -47,11 +49,10 @@ export type NzPlacement = 'bottomLeft' | 'bottomCenter' | 'bottomRight' | 'topLe ` ] }) - export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChanges { triggerWidth = 0; dropDownPosition: 'top' | 'center' | 'bottom' = 'bottom'; - positions: ConnectionPositionPair[] = [ ...DEFAULT_DROPDOWN_POSITIONS ]; + positions: ConnectionPositionPair[] = [...DEFAULT_DROPDOWN_POSITIONS]; visible$ = new Subject(); private destroy$ = new Subject(); @ContentChild(NzDropDownDirective) nzDropDownDirective: NzDropDownDirective; @@ -59,7 +60,7 @@ export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChang @ViewChild(CdkConnectedOverlay) cdkConnectedOverlay: CdkConnectedOverlay; @Input() nzTrigger: 'click' | 'hover' = 'hover'; @Input() nzOverlayClassName = ''; - @Input() nzOverlayStyle: { [ key: string ]: string } = {}; + @Input() nzOverlayStyle: { [key: string]: string } = {}; @Input() nzPlacement: NzPlacement = 'bottomLeft'; @Input() @InputBoolean() nzClickHide = true; @Input() @InputBoolean() nzDisabled = false; @@ -80,22 +81,21 @@ export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChang startSubscribe(observable$: Observable): void { const click$ = this.nzClickHide ? this.nzMenuDropdownService.menuItemClick$.pipe(mapTo(false)) : EMPTY; - combineLatest( - merge(observable$, click$), - this.nzMenuDropdownService.menuOpen$ - ).pipe( - map(value => value[ 0 ] || value[ 1 ]), - debounceTime(50), - distinctUntilChanged(), - takeUntil(this.destroy$) - ).subscribe((visible) => { - if (!this.nzDisabled && this.nzVisible !== visible) { - this.nzVisible = visible; - this.nzVisibleChange.emit(this.nzVisible); - this.triggerWidth = this.nzDropDownDirective.elementRef.nativeElement.getBoundingClientRect().width; - this.cdr.markForCheck(); - } - }); + combineLatest(merge(observable$, click$), this.nzMenuDropdownService.menuOpen$) + .pipe( + map(value => value[0] || value[1]), + debounceTime(50), + distinctUntilChanged(), + takeUntil(this.destroy$) + ) + .subscribe(visible => { + if (!this.nzDisabled && this.nzVisible !== visible) { + this.nzVisible = visible; + this.nzVisibleChange.emit(this.nzVisible); + this.triggerWidth = this.nzDropDownDirective.elementRef.nativeElement.getBoundingClientRect().width; + this.cdr.markForCheck(); + } + }); } updateDisabledState(): void { @@ -104,9 +104,11 @@ export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChang } } - constructor(protected cdr: ChangeDetectorRef, private nzMenuDropdownService: NzMenuDropdownService, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + constructor( + protected cdr: ChangeDetectorRef, + private nzMenuDropdownService: NzMenuDropdownService, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngOnDestroy(): void { this.destroy$.next(); @@ -114,7 +116,12 @@ export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChang } ngAfterContentInit(): void { - this.startSubscribe(merge(this.visible$, this.nzTrigger === 'hover' ? this.nzDropDownDirective.hover$ : this.nzDropDownDirective.$click)); + this.startSubscribe( + merge( + this.visible$, + this.nzTrigger === 'hover' ? this.nzDropDownDirective.hover$ : this.nzDropDownDirective.$click + ) + ); this.updateDisabledState(); } @@ -127,7 +134,7 @@ export class NzDropDownComponent implements OnDestroy, AfterContentInit, OnChang } if (changes.nzPlacement) { this.dropDownPosition = this.nzPlacement.indexOf('top') !== -1 ? 'top' : 'bottom'; - this.positions = [ POSITION_MAP[ this.nzPlacement ], ...this.positions ]; + this.positions = [POSITION_MAP[this.nzPlacement], ...this.positions]; } } } diff --git a/components/dropdown/nz-dropdown.directive.ts b/components/dropdown/nz-dropdown.directive.ts index c5782dfc8e3..59daec6dd30 100644 --- a/components/dropdown/nz-dropdown.directive.ts +++ b/components/dropdown/nz-dropdown.directive.ts @@ -11,7 +11,10 @@ export class NzDropDownDirective { fromEvent(this.el, 'mouseenter').pipe(mapTo(true)), fromEvent(this.el, 'mouseleave').pipe(mapTo(false)) ); - $click: Observable = fromEvent(this.el, 'click').pipe(tap(e => e.stopPropagation()), mapTo(true)); + $click: Observable = fromEvent(this.el, 'click').pipe( + tap(e => e.stopPropagation()), + mapTo(true) + ); setDisabled(disabled: boolean): void { if (disabled) { diff --git a/components/dropdown/nz-dropdown.module.ts b/components/dropdown/nz-dropdown.module.ts index 06e943bf52d..57af085c175 100644 --- a/components/dropdown/nz-dropdown.module.ts +++ b/components/dropdown/nz-dropdown.module.ts @@ -15,10 +15,15 @@ import { NzDropDownComponent } from './nz-dropdown.component'; import { NzDropDownDirective } from './nz-dropdown.directive'; @NgModule({ - imports : [ CommonModule, OverlayModule, FormsModule, NzButtonModule, NzMenuModule, NzIconModule, NzNoAnimationModule ], - entryComponents: [ NzDropdownContextComponent ], - declarations : [ NzDropDownComponent, NzDropDownButtonComponent, NzDropDownDirective, NzDropDownADirective, NzDropdownContextComponent ], - exports : [ NzDropDownComponent, NzDropDownButtonComponent, NzDropDownDirective, NzDropDownADirective ] + imports: [CommonModule, OverlayModule, FormsModule, NzButtonModule, NzMenuModule, NzIconModule, NzNoAnimationModule], + entryComponents: [NzDropdownContextComponent], + declarations: [ + NzDropDownComponent, + NzDropDownButtonComponent, + NzDropDownDirective, + NzDropDownADirective, + NzDropdownContextComponent + ], + exports: [NzDropDownComponent, NzDropDownButtonComponent, NzDropDownDirective, NzDropDownADirective] }) -export class NzDropDownModule { -} +export class NzDropDownModule {} diff --git a/components/dropdown/nz-dropdown.service.ts b/components/dropdown/nz-dropdown.service.ts index cdf8ad4e9b1..8f3e124a1d3 100644 --- a/components/dropdown/nz-dropdown.service.ts +++ b/components/dropdown/nz-dropdown.service.ts @@ -18,30 +18,37 @@ import { NzDropdownContextComponent } from './nz-dropdown-context.component'; export class NzDropdownService { private overlayRef: OverlayRef | null; - constructor(private overlay: Overlay) { - } + constructor(private overlay: Overlay) {} create($event: MouseEvent, templateRef: TemplateRef): NzDropdownContextComponent { $event.preventDefault(); this.dispose(); - this.overlayRef = this.overlay.create(new OverlayConfig({ - scrollStrategy : this.overlay.scrollStrategies.close(), - positionStrategy: this.overlay.position().flexibleConnectedTo({ - x: $event.x, - y: $event.y - }).withPositions([ - new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'top' }), - new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'bottom' }), - new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'end', overlayY: 'bottom' }), - new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'end', overlayY: 'top' }) - ]) - })); - const positionChanges = (this.overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy).positionChanges; + this.overlayRef = this.overlay.create( + new OverlayConfig({ + scrollStrategy: this.overlay.scrollStrategies.close(), + positionStrategy: this.overlay + .position() + .flexibleConnectedTo({ + x: $event.x, + y: $event.y + }) + .withPositions([ + new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'top' }), + new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'bottom' }), + new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'end', overlayY: 'bottom' }), + new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'end', overlayY: 'top' }) + ]) + }) + ); + const positionChanges = (this.overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy) + .positionChanges; const instance = this.overlayRef.attach(new ComponentPortal(NzDropdownContextComponent)).instance; - fromEvent(document, 'click').pipe( - filter(event => !!this.overlayRef && !this.overlayRef.overlayElement.contains(event.target as HTMLElement)), - take(1) - ).subscribe(() => instance.close()); + fromEvent(document, 'click') + .pipe( + filter(event => !!this.overlayRef && !this.overlayRef.overlayElement.contains(event.target as HTMLElement)), + take(1) + ) + .subscribe(() => instance.close()); instance.init(true, templateRef, positionChanges, this); return instance; } diff --git a/components/dropdown/nz-dropdown.spec.ts b/components/dropdown/nz-dropdown.spec.ts index 542810fb600..251479aeb64 100644 --- a/components/dropdown/nz-dropdown.spec.ts +++ b/components/dropdown/nz-dropdown.spec.ts @@ -25,9 +25,14 @@ describe('dropdown', () => { beforeEach(async(() => { const dir = 'ltr'; TestBed.configureTestingModule({ - imports : [ NzMenuModule, NoopAnimationsModule, NzDropDownModule, NoopAnimationsModule, NzIconTestModule ], - declarations: [ NzTestDropdownComponent, NzTestDropdownButtonComponent, NzTestDropdownWithButtonComponent, NzTestDropdownContextmenuComponent ], - providers : [ + imports: [NzMenuModule, NoopAnimationsModule, NzDropDownModule, NoopAnimationsModule, NzIconTestModule], + declarations: [ + NzTestDropdownComponent, + NzTestDropdownButtonComponent, + NzTestDropdownWithButtonComponent, + NzTestDropdownContextmenuComponent + ], + providers: [ NzDropdownService, { provide: Directionality, useFactory: () => ({ value: dir }) }, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject }) } @@ -36,13 +41,13 @@ describe('dropdown', () => { TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -89,7 +94,11 @@ describe('dropdown', () => { it('should className not add in button', () => { const buttonFixture = TestBed.createComponent(NzTestDropdownWithButtonComponent); buttonFixture.detectChanges(); - expect(buttonFixture.debugElement.query(By.directive(NzDropDownDirective)).nativeElement.classList.contains('ant-dropdown-link')).toBe(false); + expect( + buttonFixture.debugElement + .query(By.directive(NzDropDownDirective)) + .nativeElement.classList.contains('ant-dropdown-link') + ).toBe(false); }); }); describe('nz-dropdown-component', () => { @@ -117,36 +126,36 @@ describe('dropdown', () => { testComponent.visible = true; fixture.detectChanges(); let items = overlayContainerElement.querySelectorAll('.ant-dropdown-menu-item') as NodeListOf; - items[ 0 ].click(); + items[0].click(); testComponent.visible = false; fixture.detectChanges(); testComponent.visible = true; fixture.detectChanges(); items = overlayContainerElement.querySelectorAll('.ant-dropdown-menu-item') as NodeListOf; - expect(items[ 0 ].classList.contains('ant-dropdown-menu-item')).toBe(true); - expect(items[ 0 ].classList.contains('ant-dropdown-menu-item-selected')).toBe(true); + expect(items[0].classList.contains('ant-dropdown-menu-item')).toBe(true); + expect(items[0].classList.contains('ant-dropdown-menu-item-selected')).toBe(true); }); it('should selectable false work', () => { testComponent.visible = true; testComponent.selectable = false; fixture.detectChanges(); let items = overlayContainerElement.querySelectorAll('.ant-dropdown-menu-item') as NodeListOf; - items[ 0 ].click(); + items[0].click(); testComponent.visible = false; fixture.detectChanges(); testComponent.visible = true; fixture.detectChanges(); items = overlayContainerElement.querySelectorAll('.ant-dropdown-menu-item') as NodeListOf; - expect(items[ 0 ].classList.contains('ant-dropdown-menu-item')).toBe(true); - expect(items[ 0 ].classList.contains('ant-dropdown-menu-item-selected')).toBe(false); + expect(items[0].classList.contains('ant-dropdown-menu-item')).toBe(true); + expect(items[0].classList.contains('ant-dropdown-menu-item-selected')).toBe(false); }); it('should append the correct className', () => { testComponent.visible = true; testComponent.itemSelected = true; fixture.detectChanges(); const items = overlayContainerElement.querySelectorAll('.ant-dropdown-menu-item') as NodeListOf; - expect(items[ 0 ].classList.contains('.ant-menu-item-selected')).toBe(false); - expect(items[ 0 ].classList.contains('ant-dropdown-menu-item-selected')).toBe(true); + expect(items[0].classList.contains('.ant-menu-item-selected')).toBe(false); + expect(items[0].classList.contains('ant-dropdown-menu-item-selected')).toBe(true); }); it('should backdrop work with click', () => { testComponent.trigger = 'click'; @@ -171,7 +180,7 @@ describe('dropdown', () => { expect(!!link.nativeElement.attributes.getNamedItem('disabled')).toBe(true); }); it('should placement work', () => { - const placementArray = [ 'bottomLeft', 'bottomCenter', 'bottomRight', 'topLeft', 'topCenter', 'topRight' ]; + const placementArray = ['bottomLeft', 'bottomCenter', 'bottomRight', 'topLeft', 'topCenter', 'topRight']; testComponent.visible = true; placementArray.forEach(placement => { testComponent.placement = placement; @@ -306,7 +315,7 @@ describe('dropdown', () => { expect(testComponent.visibleChange).toHaveBeenCalledTimes(1); })); it('should placement work', () => { - const placementArray = [ 'bottomLeft', 'bottomCenter', 'bottomRight', 'topLeft', 'topCenter', 'topRight' ]; + const placementArray = ['bottomLeft', 'bottomCenter', 'bottomRight', 'topLeft', 'topCenter', 'topRight']; testComponent.visible = true; placementArray.forEach(placement => { testComponent.placement = placement; @@ -408,12 +417,17 @@ describe('dropdown', () => { @Component({ selector: 'nz-test-dropdown', template: ` - - - Hover me - + + Hover me - `, - styles : [] + + `, + styles: [] }) export class NzTestDropdownComponent { @ViewChild(NzDropDownComponent) nzDropDownComponent: NzDropDownComponent; @@ -451,8 +466,14 @@ export class NzTestDropdownComponent { @Component({ selector: 'nz-test-dropdown-button', template: ` - + DropDown
  • 1st menu item
  • @@ -465,8 +486,9 @@ export class NzTestDropdownComponent {
-
`, - styles : [] +
+ `, + styles: [] }) export class NzTestDropdownButtonComponent { @ViewChild(NzDropDownButtonComponent) nzDropDownButtonComponent: NzDropDownButtonComponent; @@ -495,11 +517,11 @@ export class NzTestDropdownButtonComponent { 3rd menu item - `, - styles : [] + + `, + styles: [] }) -export class NzTestDropdownWithButtonComponent { -} +export class NzTestDropdownWithButtonComponent {} @Component({ selector: 'nz-test-dropdown-contextmenu', @@ -524,11 +546,11 @@ export class NzTestDropdownWithButtonComponent { - ` + + ` }) export class NzTestDropdownContextmenuComponent { @ViewChild('template') template: TemplateRef; - constructor(public nzDropdownService: NzDropdownService) { - } + constructor(public nzDropdownService: NzDropdownService) {} } diff --git a/components/empty/demo/basic.ts b/components/empty/demo/basic.ts index a7b33ec84d7..57097a42a27 100644 --- a/components/empty/demo/basic.ts +++ b/components/empty/demo/basic.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-empty-basic', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoEmptyBasicComponent { -} +export class NzDemoEmptyBasicComponent {} diff --git a/components/empty/demo/config.ts b/components/empty/demo/config.ts index 08adb6c4822..6e8808e39bb 100644 --- a/components/empty/demo/config.ts +++ b/components/empty/demo/config.ts @@ -8,7 +8,8 @@ import { NzEmptyService } from 'ng-zorro-antd'; [nzUnCheckedChildren]="'default'" [nzCheckedChildren]="'customize'" [(ngModel)]="customize" - (ngModelChange)="onConfigChange()"> + (ngModelChange)="onConfigChange()" + > @@ -28,10 +29,10 @@ import { NzEmptyService } from 'ng-zorro-antd';

Table

- - Title - Age - + + Title + Age + @@ -45,10 +46,13 @@ import { NzEmptyService } from 'ng-zorro-antd';
`, - styles : [ `h3 { - font-size: inherit; - margin: 16px 0 8px 0; - }` + styles: [ + ` + h3 { + font-size: inherit; + margin: 16px 0 8px 0; + } + ` ] }) export class NzDemoEmptyConfigComponent { @@ -56,8 +60,7 @@ export class NzDemoEmptyConfigComponent { customize = false; - constructor(private nzEmptyService: NzEmptyService) { - } + constructor(private nzEmptyService: NzEmptyService) {} onConfigChange(): void { if (this.customize) { diff --git a/components/empty/demo/customize.ts b/components/empty/demo/customize.ts index ccbdc8eba23..ac0808003dd 100644 --- a/components/empty/demo/customize.ts +++ b/components/empty/demo/customize.ts @@ -4,19 +4,21 @@ import { Component } from '@angular/core'; selector: 'nz-demo-empty-customize', template: ` + [nzNotFoundFooter]="footerTpl" + > - - Customize Description - + Customize Description - `, - styles : [] + + `, + styles: [] }) export class NzDemoEmptyCustomizeComponent { onClick(): void { diff --git a/components/empty/nz-embed-empty.component.ts b/components/empty/nz-embed-empty.component.ts index c91e6e67243..ba1d4865897 100644 --- a/components/empty/nz-embed-empty.component.ts +++ b/components/empty/nz-embed-empty.component.ts @@ -9,7 +9,8 @@ import { OnDestroy, OnInit, SimpleChanges, - TemplateRef, Type, + TemplateRef, + Type, ViewContainerRef, ViewEncapsulation } from '@angular/core'; @@ -21,9 +22,9 @@ import { NzEmptyService } from './nz-empty.service'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-embed-empty', - templateUrl : './nz-embed-empty.component.html' + encapsulation: ViewEncapsulation.None, + selector: 'nz-embed-empty', + templateUrl: './nz-embed-empty.component.html' }) export class NzEmbedEmptyComponent implements OnChanges, OnInit, OnDestroy { @Input() nzComponentName: string; @@ -42,8 +43,7 @@ export class NzEmbedEmptyComponent implements OnChanges, OnInit, OnDestroy { private viewContainerRef: ViewContainerRef, private cdr: ChangeDetectorRef, private injector: Injector - ) { - } + ) {} ngOnChanges(changes: SimpleChanges): void { if (changes.nzComponentName) { @@ -54,7 +54,7 @@ export class NzEmbedEmptyComponent implements OnChanges, OnInit, OnDestroy { this.content = changes.specificContent.currentValue; this.renderEmpty(); } - } + } ngOnInit(): void { const userContent_ = this.emptyService.userDefaultContent$.subscribe(content => { @@ -94,7 +94,7 @@ export class NzEmbedEmptyComponent implements OnChanges, OnInit, OnDestroy { this.contentType = 'template'; this.contentPortal = new TemplatePortal(content, this.viewContainerRef, context); } else if (content instanceof Type) { - const context = new WeakMap([ [ NZ_EMPTY_COMPONENT_NAME, this.nzComponentName ] ]); + const context = new WeakMap([[NZ_EMPTY_COMPONENT_NAME, this.nzComponentName]]); const injector = new PortalInjector(this.injector, context); this.contentType = 'component'; this.contentPortal = new ComponentPortal(content, this.viewContainerRef, injector); diff --git a/components/empty/nz-empty-config.ts b/components/empty/nz-empty-config.ts index e4a89468a93..cc750b06b3e 100644 --- a/components/empty/nz-empty-config.ts +++ b/components/empty/nz-empty-config.ts @@ -10,6 +10,8 @@ export const NZ_DEFAULT_EMPTY_CONTENT = new InjectionToken>('nz-empty- export const NZ_EMPTY_COMPONENT_NAME = new InjectionToken('nz-empty-component-name'); -export const emptyImage = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTg0IiBoZWlnaHQ9IjE1MiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDI0IDMxLjY3KSI+PGVsbGlwc2UgZmlsbC1vcGFjaXR5PSIuOCIgZmlsbD0iI0Y1RjVGNyIgY3g9IjY3Ljc5NyIgY3k9IjEwNi44OSIgcng9IjY3Ljc5NyIgcnk9IjEyLjY2OCIvPjxwYXRoIGQ9Ik0xMjIuMDM0IDY5LjY3NEw5OC4xMDkgNDAuMjI5Yy0xLjE0OC0xLjM4Ni0yLjgyNi0yLjIyNS00LjU5My0yLjIyNWgtNTEuNDRjLTEuNzY2IDAtMy40NDQuODM5LTQuNTkyIDIuMjI1TDEzLjU2IDY5LjY3NHYxNS4zODNoMTA4LjQ3NVY2OS42NzR6IiBmaWxsPSIjQUVCOEMyIi8+PHBhdGggZD0iTTEwMS41MzcgODYuMjE0TDgwLjYzIDYxLjEwMmMtMS4wMDEtMS4yMDctMi41MDctMS44NjctNC4wNDgtMS44NjdIMzEuNzI0Yy0xLjU0IDAtMy4wNDcuNjYtNC4wNDggMS44NjdMNi43NjkgODYuMjE0djEzLjc5Mmg5NC43NjhWODYuMjE0eiIgZmlsbD0idXJsKCNsaW5lYXJHcmFkaWVudC0xKSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMuNTYpIi8+PHBhdGggZD0iTTMzLjgzIDBoNjcuOTMzYTQgNCAwIDAgMSA0IDR2OTMuMzQ0YTQgNCAwIDAgMS00IDRIMzMuODNhNCA0IDAgMCAxLTQtNFY0YTQgNCAwIDAgMSA0LTR6IiBmaWxsPSIjRjVGNUY3Ii8+PHBhdGggZD0iTTQyLjY3OCA5Ljk1M2g1MC4yMzdhMiAyIDAgMCAxIDIgMlYzNi45MWEyIDIgMCAwIDEtMiAySDQyLjY3OGEyIDIgMCAwIDEtMi0yVjExLjk1M2EyIDIgMCAwIDEgMi0yek00Mi45NCA0OS43NjdoNDkuNzEzYTIuMjYyIDIuMjYyIDAgMSAxIDAgNC41MjRINDIuOTRhMi4yNjIgMi4yNjIgMCAwIDEgMC00LjUyNHpNNDIuOTQgNjEuNTNoNDkuNzEzYTIuMjYyIDIuMjYyIDAgMSAxIDAgNC41MjVINDIuOTRhMi4yNjIgMi4yNjIgMCAwIDEgMC00LjUyNXpNMTIxLjgxMyAxMDUuMDMyYy0uNzc1IDMuMDcxLTMuNDk3IDUuMzYtNi43MzUgNS4zNkgyMC41MTVjLTMuMjM4IDAtNS45Ni0yLjI5LTYuNzM0LTUuMzZhNy4zMDkgNy4zMDkgMCAwIDEtLjIyMi0xLjc5VjY5LjY3NWgyNi4zMThjMi45MDcgMCA1LjI1IDIuNDQ4IDUuMjUgNS40MnYuMDRjMCAyLjk3MSAyLjM3IDUuMzcgNS4yNzcgNS4zN2gzNC43ODVjMi45MDcgMCA1LjI3Ny0yLjQyMSA1LjI3Ny01LjM5M1Y3NS4xYzAtMi45NzIgMi4zNDMtNS40MjYgNS4yNS01LjQyNmgyNi4zMTh2MzMuNTY5YzAgLjYxNy0uMDc3IDEuMjE2LS4yMjEgMS43ODl6IiBmaWxsPSIjRENFMEU2Ii8+PC9nPjxwYXRoIGQ9Ik0xNDkuMTIxIDMzLjI5MmwtNi44MyAyLjY1YTEgMSAwIDAgMS0xLjMxNy0xLjIzbDEuOTM3LTYuMjA3Yy0yLjU4OS0yLjk0NC00LjEwOS02LjUzNC00LjEwOS0xMC40MDhDMTM4LjgwMiA4LjEwMiAxNDguOTIgMCAxNjEuNDAyIDAgMTczLjg4MSAwIDE4NCA4LjEwMiAxODQgMTguMDk3YzAgOS45OTUtMTAuMTE4IDE4LjA5Ny0yMi41OTkgMTguMDk3LTQuNTI4IDAtOC43NDQtMS4wNjYtMTIuMjgtMi45MDJ6IiBmaWxsPSIjRENFMEU2Ii8+PGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTQ5LjY1IDE1LjM4MykiIGZpbGw9IiNGRkYiPjxlbGxpcHNlIGN4PSIyMC42NTQiIGN5PSIzLjE2NyIgcng9IjIuODQ5IiByeT0iMi44MTUiLz48cGF0aCBkPSJNNS42OTggNS42M0gwTDIuODk4LjcwNHpNOS4yNTkuNzA0aDQuOTg1VjUuNjNIOS4yNTl6Ii8+PC9nPjwvZz48L3N2Zz4='; +export const emptyImage = + 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTg0IiBoZWlnaHQ9IjE1MiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDI0IDMxLjY3KSI+PGVsbGlwc2UgZmlsbC1vcGFjaXR5PSIuOCIgZmlsbD0iI0Y1RjVGNyIgY3g9IjY3Ljc5NyIgY3k9IjEwNi44OSIgcng9IjY3Ljc5NyIgcnk9IjEyLjY2OCIvPjxwYXRoIGQ9Ik0xMjIuMDM0IDY5LjY3NEw5OC4xMDkgNDAuMjI5Yy0xLjE0OC0xLjM4Ni0yLjgyNi0yLjIyNS00LjU5My0yLjIyNWgtNTEuNDRjLTEuNzY2IDAtMy40NDQuODM5LTQuNTkyIDIuMjI1TDEzLjU2IDY5LjY3NHYxNS4zODNoMTA4LjQ3NVY2OS42NzR6IiBmaWxsPSIjQUVCOEMyIi8+PHBhdGggZD0iTTEwMS41MzcgODYuMjE0TDgwLjYzIDYxLjEwMmMtMS4wMDEtMS4yMDctMi41MDctMS44NjctNC4wNDgtMS44NjdIMzEuNzI0Yy0xLjU0IDAtMy4wNDcuNjYtNC4wNDggMS44NjdMNi43NjkgODYuMjE0djEzLjc5Mmg5NC43NjhWODYuMjE0eiIgZmlsbD0idXJsKCNsaW5lYXJHcmFkaWVudC0xKSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMuNTYpIi8+PHBhdGggZD0iTTMzLjgzIDBoNjcuOTMzYTQgNCAwIDAgMSA0IDR2OTMuMzQ0YTQgNCAwIDAgMS00IDRIMzMuODNhNCA0IDAgMCAxLTQtNFY0YTQgNCAwIDAgMSA0LTR6IiBmaWxsPSIjRjVGNUY3Ii8+PHBhdGggZD0iTTQyLjY3OCA5Ljk1M2g1MC4yMzdhMiAyIDAgMCAxIDIgMlYzNi45MWEyIDIgMCAwIDEtMiAySDQyLjY3OGEyIDIgMCAwIDEtMi0yVjExLjk1M2EyIDIgMCAwIDEgMi0yek00Mi45NCA0OS43NjdoNDkuNzEzYTIuMjYyIDIuMjYyIDAgMSAxIDAgNC41MjRINDIuOTRhMi4yNjIgMi4yNjIgMCAwIDEgMC00LjUyNHpNNDIuOTQgNjEuNTNoNDkuNzEzYTIuMjYyIDIuMjYyIDAgMSAxIDAgNC41MjVINDIuOTRhMi4yNjIgMi4yNjIgMCAwIDEgMC00LjUyNXpNMTIxLjgxMyAxMDUuMDMyYy0uNzc1IDMuMDcxLTMuNDk3IDUuMzYtNi43MzUgNS4zNkgyMC41MTVjLTMuMjM4IDAtNS45Ni0yLjI5LTYuNzM0LTUuMzZhNy4zMDkgNy4zMDkgMCAwIDEtLjIyMi0xLjc5VjY5LjY3NWgyNi4zMThjMi45MDcgMCA1LjI1IDIuNDQ4IDUuMjUgNS40MnYuMDRjMCAyLjk3MSAyLjM3IDUuMzcgNS4yNzcgNS4zN2gzNC43ODVjMi45MDcgMCA1LjI3Ny0yLjQyMSA1LjI3Ny01LjM5M1Y3NS4xYzAtMi45NzIgMi4zNDMtNS40MjYgNS4yNS01LjQyNmgyNi4zMTh2MzMuNTY5YzAgLjYxNy0uMDc3IDEuMjE2LS4yMjEgMS43ODl6IiBmaWxsPSIjRENFMEU2Ii8+PC9nPjxwYXRoIGQ9Ik0xNDkuMTIxIDMzLjI5MmwtNi44MyAyLjY1YTEgMSAwIDAgMS0xLjMxNy0xLjIzbDEuOTM3LTYuMjA3Yy0yLjU4OS0yLjk0NC00LjEwOS02LjUzNC00LjEwOS0xMC40MDhDMTM4LjgwMiA4LjEwMiAxNDguOTIgMCAxNjEuNDAyIDAgMTczLjg4MSAwIDE4NCA4LjEwMiAxODQgMTguMDk3YzAgOS45OTUtMTAuMTE4IDE4LjA5Ny0yMi41OTkgMTguMDk3LTQuNTI4IDAtOC43NDQtMS4wNjYtMTIuMjgtMi45MDJ6IiBmaWxsPSIjRENFMEU2Ii8+PGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTQ5LjY1IDE1LjM4MykiIGZpbGw9IiNGRkYiPjxlbGxpcHNlIGN4PSIyMC42NTQiIGN5PSIzLjE2NyIgcng9IjIuODQ5IiByeT0iMi44MTUiLz48cGF0aCBkPSJNNS42OTggNS42M0gwTDIuODk4LjcwNHpNOS4yNTkuNzA0aDQuOTg1VjUuNjNIOS4yNTl6Ii8+PC9nPjwvZz48L3N2Zz4='; -export const simpleEmptyImage = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iNjRweCIgaGVpZ2h0PSI0MXB4IiB2aWV3Qm94PSIwIDAgNjQgNDEiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDUyLjUgKDY3NDY5KSAtIGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCAtLT4KICAgIDxnIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC00NzIuMDAwMDAwLCAtMTMzNS4wMDAwMDApIj4KICAgICAgICAgICAgPGcgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDY0LjAwMDAwMCwgMTExNC4wMDAwMDApIj4KICAgICAgICAgICAgICAgIDxnICB0cmFuc2Zvcm09InRyYW5zbGF0ZSg0MC4wMDAwMDAsIDc4LjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgzNjguMDAwMDAwLCAxNDQuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICAgICAgICAgIDxnID4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxlbGxpcHNlICBmaWxsPSIjRjVGNUY1IiBjeD0iMzIiIGN5PSIzMyIgcng9IjMyIiByeT0iNyI+PC9lbGxpcHNlPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgPGcgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSg5LjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHN0cm9rZT0iI0Q5RDlEOSI+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTQ2LDEyLjc2MDU2MDQgTDM1Ljg1NDMwNDcsMS4yNTczOTYzMyBDMzUuMzY3NDQxNCwwLjQ3MzgyNjYwNSAzNC42NTU4Nzg5LDAgMzMuOTA2NzYxNywwIEwxMi4wOTMyMzgzLDAgQzExLjM0NDEyMTEsMCAxMC42MzI1NTg2LDAuNDczOTUwMjU1IDEwLjE0NTY5NTMsMS4yNTczOTYzMyBMMi42MTQ3OTcyN2UtMTIsMTIuNzYwNTYwNCBMMCwyMiBMNDYsMjIgTDQ2LDEyLjc2MDU2MDQgWiIgID48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTMyLjYxMzI4MTMsMTUuOTMxNSBDMzIuNjEzMjgxMywxNC4zMjU4NTExIDMzLjYwNjk1MzEsMTMuMDAwMjM0IDM0LjgzOTY5OTIsMTMgTDQ2LDEzIEw0NiwzMS4xMzcxMjc3IEM0NiwzMy4yNTg5NTc0IDQ0LjY3OTM4NjcsMzUgNDMuMDUwNDI5NywzNSBMMi45NDk1NzAzMSwzNSBDMS4zMjA1MjM0NCwzNSAwLDMzLjI1ODg0MDQgMCwzMS4xMzcxMjc3IEwwLDEzIEwxMS4xNjAzMDA4LDEzIEMxMi4zOTMwNDY5LDEzIDEzLjM4NjcxODgsMTQuMzIyODA4NSAxMy4zODY3MTg4LDE1LjkyODQ1NzQgTDEzLjM4NjcxODgsMTUuOTQ5NjM4MyBDMTMuMzg2NzE4OCwxNy41NTUyODcyIDE0LjM5MTcxMDksMTguODUxMTgwOSAxNS42MjQ0NTcsMTguODUxMTgwOSBMMzAuMzc1NTQzLDE4Ljg1MTE4MDkgQzMxLjYwODI4OTEsMTguODUxMTgwOSAzMi42MTMyODEzLDE3LjU0MzM1MTEgMzIuNjEzMjgxMywxNS45Mzc3MDIxIEwzMi42MTMyODEzLDE1LjkzMTUgWiIgIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+'; +export const simpleEmptyImage = + 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iNjRweCIgaGVpZ2h0PSI0MXB4IiB2aWV3Qm94PSIwIDAgNjQgNDEiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDUyLjUgKDY3NDY5KSAtIGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCAtLT4KICAgIDxnIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgICAgIDxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC00NzIuMDAwMDAwLCAtMTMzNS4wMDAwMDApIj4KICAgICAgICAgICAgPGcgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDY0LjAwMDAwMCwgMTExNC4wMDAwMDApIj4KICAgICAgICAgICAgICAgIDxnICB0cmFuc2Zvcm09InRyYW5zbGF0ZSg0MC4wMDAwMDAsIDc4LjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgzNjguMDAwMDAwLCAxNDQuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICAgICAgICAgIDxnID4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxlbGxpcHNlICBmaWxsPSIjRjVGNUY1IiBjeD0iMzIiIGN5PSIzMyIgcng9IjMyIiByeT0iNyI+PC9lbGxpcHNlPgogICAgICAgICAgICAgICAgICAgICAgICAgICAgPGcgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSg5LjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHN0cm9rZT0iI0Q5RDlEOSI+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTQ2LDEyLjc2MDU2MDQgTDM1Ljg1NDMwNDcsMS4yNTczOTYzMyBDMzUuMzY3NDQxNCwwLjQ3MzgyNjYwNSAzNC42NTU4Nzg5LDAgMzMuOTA2NzYxNywwIEwxMi4wOTMyMzgzLDAgQzExLjM0NDEyMTEsMCAxMC42MzI1NTg2LDAuNDczOTUwMjU1IDEwLjE0NTY5NTMsMS4yNTczOTYzMyBMMi42MTQ3OTcyN2UtMTIsMTIuNzYwNTYwNCBMMCwyMiBMNDYsMjIgTDQ2LDEyLjc2MDU2MDQgWiIgID48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTMyLjYxMzI4MTMsMTUuOTMxNSBDMzIuNjEzMjgxMywxNC4zMjU4NTExIDMzLjYwNjk1MzEsMTMuMDAwMjM0IDM0LjgzOTY5OTIsMTMgTDQ2LDEzIEw0NiwzMS4xMzcxMjc3IEM0NiwzMy4yNTg5NTc0IDQ0LjY3OTM4NjcsMzUgNDMuMDUwNDI5NywzNSBMMi45NDk1NzAzMSwzNSBDMS4zMjA1MjM0NCwzNSAwLDMzLjI1ODg0MDQgMCwzMS4xMzcxMjc3IEwwLDEzIEwxMS4xNjAzMDA4LDEzIEMxMi4zOTMwNDY5LDEzIDEzLjM4NjcxODgsMTQuMzIyODA4NSAxMy4zODY3MTg4LDE1LjkyODQ1NzQgTDEzLjM4NjcxODgsMTUuOTQ5NjM4MyBDMTMuMzg2NzE4OCwxNy41NTUyODcyIDE0LjM5MTcxMDksMTguODUxMTgwOSAxNS42MjQ0NTcsMTguODUxMTgwOSBMMzAuMzc1NTQzLDE4Ljg1MTE4MDkgQzMxLjYwODI4OTEsMTguODUxMTgwOSAzMi42MTMyODEzLDE3LjU0MzM1MTEgMzIuNjEzMjgxMywxNS45Mzc3MDIxIEwzMi42MTMyODEzLDE1LjkzMTUgWiIgIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+'; diff --git a/components/empty/nz-empty-error.ts b/components/empty/nz-empty-error.ts index 7a1a22e360c..d38808a9ed3 100644 --- a/components/empty/nz-empty-error.ts +++ b/components/empty/nz-empty-error.ts @@ -1,3 +1,4 @@ -export function getEmptyContentTypeError(content: any): Error { // tslint:disable-line:no-any +// tslint:disable-next-line:no-any +export function getEmptyContentTypeError(content: any): Error { return TypeError(`[NG-ZORRO]: useDefaultContent expect 'string', 'templateRef' or 'component' but get ${content}`); } diff --git a/components/empty/nz-empty.component.ts b/components/empty/nz-empty.component.ts index dfc6242bc8e..37bf52ca09e 100644 --- a/components/empty/nz-empty.component.ts +++ b/components/empty/nz-empty.component.ts @@ -1,8 +1,11 @@ import { - ChangeDetectionStrategy, ChangeDetectorRef, + ChangeDetectionStrategy, + ChangeDetectorRef, Component, Input, - OnChanges, OnDestroy, OnInit, + OnChanges, + OnDestroy, + OnInit, SimpleChanges, TemplateRef, ViewEncapsulation @@ -16,12 +19,12 @@ import { emptyImage } from './nz-empty-config'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-empty', - templateUrl : './nz-empty.component.html', - styles : [ 'nz-empty { display: block; }' ], - host : { - 'class': 'ant-empty' + encapsulation: ViewEncapsulation.None, + selector: 'nz-empty', + templateUrl: './nz-empty.component.html', + styles: ['nz-empty { display: block; }'], + host: { + class: 'ant-empty' } }) export class NzEmptyComponent implements OnChanges, OnInit, OnDestroy { @@ -37,7 +40,7 @@ export class NzEmptyComponent implements OnChanges, OnInit, OnDestroy { defaultSvg = this.sanitizer.bypassSecurityTrustResourceUrl(emptyImage); isContentString = false; - locale: { [ key: string ]: string } = {}; + locale: { [key: string]: string } = {}; get shouldRenderContent(): boolean { const content = this.nzNotFoundContent; @@ -46,12 +49,7 @@ export class NzEmptyComponent implements OnChanges, OnInit, OnDestroy { private destroy$ = new Subject(); - constructor( - private sanitizer: DomSanitizer, - private i18n: NzI18nService, - private cdr: ChangeDetectorRef - ) { - } + constructor(private sanitizer: DomSanitizer, private i18n: NzI18nService, private cdr: ChangeDetectorRef) {} ngOnChanges(changes: SimpleChanges): void { const { nzNotFoundContent } = changes; @@ -61,9 +59,7 @@ export class NzEmptyComponent implements OnChanges, OnInit, OnDestroy { } ngOnInit(): void { - this.i18n.localeChange.pipe( - takeUntil(this.destroy$) - ).subscribe(() => { + this.i18n.localeChange.pipe(takeUntil(this.destroy$)).subscribe(() => { this.locale = this.i18n.getLocaleData('Empty'); this.cdr.markForCheck(); }); diff --git a/components/empty/nz-empty.module.ts b/components/empty/nz-empty.module.ts index 023e33f7b0a..fa05eee8113 100644 --- a/components/empty/nz-empty.module.ts +++ b/components/empty/nz-empty.module.ts @@ -7,9 +7,8 @@ import { NzEmbedEmptyComponent } from './nz-embed-empty.component'; import { NzEmptyComponent } from './nz-empty.component'; @NgModule({ - imports : [ CommonModule, PortalModule, NzAddOnModule, NzI18nModule ], - declarations: [ NzEmptyComponent, NzEmbedEmptyComponent ], - exports : [ NzEmptyComponent, NzEmbedEmptyComponent ] + imports: [CommonModule, PortalModule, NzAddOnModule, NzI18nModule], + declarations: [NzEmptyComponent, NzEmbedEmptyComponent], + exports: [NzEmptyComponent, NzEmbedEmptyComponent] }) -export class NzEmptyModule { -} +export class NzEmptyModule {} diff --git a/components/empty/nz-empty.service.ts b/components/empty/nz-empty.service.ts index a2516f647a9..e634f3bd618 100644 --- a/components/empty/nz-empty.service.ts +++ b/components/empty/nz-empty.service.ts @@ -6,7 +6,8 @@ import { getEmptyContentTypeError } from './nz-empty-error'; @Injectable({ providedIn: 'root' }) -export class NzEmptyService { // tslint:disable-line:no-any +// tslint:disable-next-line:no-any +export class NzEmptyService { userDefaultContent$ = new BehaviorSubject(undefined); constructor(@Inject(NZ_DEFAULT_EMPTY_CONTENT) @Optional() private defaultEmptyContent: Type) { @@ -16,11 +17,12 @@ export class NzEmptyService { // tslint:disable-line:no-any } setDefaultContent(content?: NzEmptyCustomContent): void { - if (typeof content === 'string' - || content === undefined - || content === null - || content instanceof TemplateRef - || content instanceof Type + if ( + typeof content === 'string' || + content === undefined || + content === null || + content instanceof TemplateRef || + content instanceof Type ) { this.userDefaultContent$.next(content); } else { diff --git a/components/empty/nz-empty.spec.ts b/components/empty/nz-empty.spec.ts index 5750d2e1def..7d9ae888fab 100644 --- a/components/empty/nz-empty.spec.ts +++ b/components/empty/nz-empty.spec.ts @@ -22,8 +22,8 @@ describe('nz-empty', () => { beforeEach(() => { testBed = TestBed.configureTestingModule({ - imports : [ CommonModule, NzEmptyModule ], - declarations: [ NzEmptyTestBasicComponent ] + imports: [CommonModule, NzEmptyModule], + declarations: [NzEmptyTestBasicComponent] }); TestBed.compileComponents(); @@ -133,14 +133,14 @@ describe('nz-empty', () => { describe('service method', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ NzEmptyTestServiceModule ] + imports: [NzEmptyTestServiceModule] }).compileComponents(); fixture = TestBed.createComponent(NzEmptyTestServiceComponent); testComponent = fixture.debugElement.componentInstance; }); - it('should components\' prop has priority', fakeAsync(() => { + it("should components' prop has priority", fakeAsync(() => { const refresh = () => { fixture.detectChanges(); tick(); @@ -180,7 +180,6 @@ describe('nz-empty', () => { })); it('should raise error when set a invalid default value', () => { - expect(() => { // tslint:disable-next-line:no-any testComponent.emptyService.setDefaultContent(false as any); @@ -260,7 +259,7 @@ describe('nz-empty', () => { describe('service injection', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports: [ NzEmptyTestInjectionModule ] + imports: [NzEmptyTestInjectionModule] }).compileComponents(); fixture = TestBed.createComponent(NzEmptyTestServiceComponent); @@ -325,8 +324,7 @@ export class NzEmptyTestServiceComponent { noResult?: string | null; - constructor(public emptyService: NzEmptyService) { - } + constructor(public emptyService: NzEmptyService) {} reset(): void { this.emptyService.resetDefault(); @@ -344,30 +342,27 @@ export class NzEmptyTestServiceComponent { ` }) export class NzEmptyTestCustomComponent { - constructor(@Inject(NZ_EMPTY_COMPONENT_NAME) public name: string) { - } + constructor(@Inject(NZ_EMPTY_COMPONENT_NAME) public name: string) {} } @NgModule({ - imports : [ CommonModule, NzEmptyModule, NzListModule ], - declarations : [ NzEmptyTestServiceComponent, NzEmptyTestCustomComponent ], - entryComponents: [ NzEmptyTestCustomComponent ], - exports : [ NzEmptyTestServiceComponent, NzEmptyTestCustomComponent ] + imports: [CommonModule, NzEmptyModule, NzListModule], + declarations: [NzEmptyTestServiceComponent, NzEmptyTestCustomComponent], + entryComponents: [NzEmptyTestCustomComponent], + exports: [NzEmptyTestServiceComponent, NzEmptyTestCustomComponent] }) -export class NzEmptyTestServiceModule { -} +export class NzEmptyTestServiceModule {} @NgModule({ - imports : [ CommonModule, NzEmptyModule, NzListModule ], - declarations : [ NzEmptyTestServiceComponent, NzEmptyTestCustomComponent ], - entryComponents: [ NzEmptyTestCustomComponent ], - exports : [ NzEmptyTestServiceComponent, NzEmptyTestCustomComponent ], - providers : [ + imports: [CommonModule, NzEmptyModule, NzListModule], + declarations: [NzEmptyTestServiceComponent, NzEmptyTestCustomComponent], + entryComponents: [NzEmptyTestCustomComponent], + exports: [NzEmptyTestServiceComponent, NzEmptyTestCustomComponent], + providers: [ { - provide : NZ_DEFAULT_EMPTY_CONTENT, + provide: NZ_DEFAULT_EMPTY_CONTENT, useValue: NzEmptyTestCustomComponent } ] }) -export class NzEmptyTestInjectionModule { -} +export class NzEmptyTestInjectionModule {} diff --git a/components/form/demo/advanced-search.ts b/components/form/demo/advanced-search.ts index 79419375465..7d25e34811b 100644 --- a/components/form/demo/advanced-search.ts +++ b/components/form/demo/advanced-search.ts @@ -1,20 +1,21 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormControl, - FormGroup -} from '@angular/forms'; +import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; @Component({ selector: 'nz-demo-form-advanced-search', template: `
-
+
- Field {{control.index}} + Field {{ control.index }} - +
@@ -25,7 +26,7 @@ import { Collapse - +
@@ -36,7 +37,7 @@ import { `, styles: [ - ` + ` .ant-advanced-search-form { padding: 24px; background: #fbfbfb; @@ -72,7 +73,7 @@ export class NzDemoFormAdvancedSearchComponent implements OnInit { toggleCollapse(): void { this.isCollapse = !this.isCollapse; this.controlArray.forEach((c, index) => { - c.show = this.isCollapse ? (index < 6) : true; + c.show = this.isCollapse ? index < 6 : true; }); } @@ -80,8 +81,7 @@ export class NzDemoFormAdvancedSearchComponent implements OnInit { this.validateForm.reset(); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({}); diff --git a/components/form/demo/coordinated.ts b/components/form/demo/coordinated.ts index 45b5199b8c7..249041d9939 100644 --- a/components/form/demo/coordinated.ts +++ b/components/form/demo/coordinated.ts @@ -1,9 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-coordinated', @@ -12,18 +8,27 @@ import { Note - - Please input your username! + + Please input your username! Gender - + - Please select your gender! + Please select your gender! @@ -33,10 +38,12 @@ import { `, - styles : [ - `[nz-form] { - max-width: 600px; - }` + styles: [ + ` + [nz-form] { + max-width: 600px; + } + ` ] }) export class NzDemoFormCoordinatedComponent implements OnInit { @@ -44,8 +51,8 @@ export class NzDemoFormCoordinatedComponent implements OnInit { submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } @@ -53,13 +60,12 @@ export class NzDemoFormCoordinatedComponent implements OnInit { this.validateForm.get('note')!.setValue(value === 'male' ? 'Hi, man!' : 'Hi, lady!'); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - note : [ null, [ Validators.required ] ], - gender: [ null, [ Validators.required ] ] + note: [null, [Validators.required]], + gender: [null, [Validators.required]] }); } } diff --git a/components/form/demo/dynamic-form-item.ts b/components/form/demo/dynamic-form-item.ts index e5099ecd5a4..4250f19a31e 100644 --- a/components/form/demo/dynamic-form-item.ts +++ b/components/form/demo/dynamic-form-item.ts @@ -1,33 +1,42 @@ import { Component, OnInit } from '@angular/core'; -import { - AbstractControl, - FormBuilder, - FormControl, - FormGroup, - Validators -} from '@angular/forms'; +import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-dynamic-form-item', template: `
- - Passengers - - - - + + Passengers + + + + Please input passenger's name or delete this field. - - + + - + @@ -35,14 +44,14 @@ import { `, styles: [ - ` + ` .dynamic-delete-button { cursor: pointer; position: relative; top: 4px; font-size: 24px; color: #999; - transition: all .3s; + transition: all 0.3s; } .dynamic-delete-button:hover { @@ -57,24 +66,27 @@ import { }) export class NzDemoFormDynamicFormItemComponent implements OnInit { validateForm: FormGroup; - controlArray: Array<{ id: number, controlInstance: string }> = []; + controlArray: Array<{ id: number; controlInstance: string }> = []; addField(e?: MouseEvent): void { if (e) { e.preventDefault(); } - const id = (this.controlArray.length > 0) ? this.controlArray[ this.controlArray.length - 1 ].id + 1 : 0; + const id = this.controlArray.length > 0 ? this.controlArray[this.controlArray.length - 1].id + 1 : 0; const control = { id, controlInstance: `passenger${id}` }; const index = this.controlArray.push(control); - console.log(this.controlArray[ this.controlArray.length - 1 ]); - this.validateForm.addControl(this.controlArray[ index - 1 ].controlInstance, new FormControl(null, Validators.required)); + console.log(this.controlArray[this.controlArray.length - 1]); + this.validateForm.addControl( + this.controlArray[index - 1].controlInstance, + new FormControl(null, Validators.required) + ); } - removeField(i: { id: number, controlInstance: string }, e: MouseEvent): void { + removeField(i: { id: number; controlInstance: string }, e: MouseEvent): void { e.preventDefault(); if (this.controlArray.length > 1) { const index = this.controlArray.indexOf(i); @@ -85,19 +97,18 @@ export class NzDemoFormDynamicFormItemComponent implements OnInit { } getFormControl(name: string): AbstractControl { - return this.validateForm.controls[ name ]; + return this.validateForm.controls[name]; } submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } console.log(this.validateForm.value); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({}); diff --git a/components/form/demo/dynamic-rule.ts b/components/form/demo/dynamic-rule.ts index 81012110463..22525b2f66b 100644 --- a/components/form/demo/dynamic-rule.ts +++ b/components/form/demo/dynamic-rule.ts @@ -1,9 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-dynamic-rule', @@ -12,20 +8,28 @@ import { Name - - Please input your name + + Please input your name - Nickname + Nickname - - Please input your nickname + + Please input your nickname - + @@ -41,8 +45,8 @@ export class NzDemoFormDynamicRuleComponent implements OnInit { submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } @@ -57,14 +61,13 @@ export class NzDemoFormDynamicRuleComponent implements OnInit { this.validateForm.get('nickname')!.updateValueAndValidity(); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - name : [ null, [ Validators.required ] ], - nickname: [ null ], - required: [ false ] + name: [null, [Validators.required]], + nickname: [null], + required: [false] }); } } diff --git a/components/form/demo/horizontal-login.ts b/components/form/demo/horizontal-login.ts index 2a94524a390..588ed503c7e 100644 --- a/components/form/demo/horizontal-login.ts +++ b/components/form/demo/horizontal-login.ts @@ -1,9 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-horizontal-login', @@ -12,17 +8,21 @@ import { - + - Please input your username! + Please input your username! - + - Please input your Password! + Please input your Password! @@ -33,26 +33,25 @@ import { -` + ` }) export class NzDemoFormHorizontalLoginComponent implements OnInit { validateForm: FormGroup; submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - userName: [ null, [ Validators.required ] ], - password: [ null, [ Validators.required ] ], - remember: [ true ] + userName: [null, [Validators.required]], + password: [null, [Validators.required]], + remember: [true] }); } } diff --git a/components/form/demo/layout.ts b/components/form/demo/layout.ts index ea5646c5dba..d35fd92087c 100644 --- a/components/form/demo/layout.ts +++ b/components/form/demo/layout.ts @@ -1,17 +1,18 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-layout', template: ` -
+ - Form Layout - + Form Layout + @@ -20,27 +21,32 @@ import { - Field A - - - Please input your username! + Field A + + + Please input your username! - Field B - - - Please input your Password! + Field B + + + Please input your Password! - + -
`, - styles : [ - ` + + `, + styles: [ + ` [nz-form]:not(.ant-form-inline):not(.ant-form-vertical) { max-width: 600px; } @@ -52,8 +58,8 @@ export class NzDemoFormLayoutComponent implements OnInit { submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } @@ -61,14 +67,13 @@ export class NzDemoFormLayoutComponent implements OnInit { return this.validateForm.controls.formLayout && this.validateForm.controls.formLayout.value === 'horizontal'; } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - formLayout: [ 'horizontal' ], - fieldA : [ null, [ Validators.required ] ], - filedB : [ null, [ Validators.required ] ] + formLayout: ['horizontal'], + fieldA: [null, [Validators.required]], + filedB: [null, [Validators.required]] }); } } diff --git a/components/form/demo/normal-login.ts b/components/form/demo/normal-login.ts index 1c58cd8e6e9..22a80405761 100644 --- a/components/form/demo/normal-login.ts +++ b/components/form/demo/normal-login.ts @@ -1,9 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-normal-login', @@ -12,17 +8,21 @@ import { - + - Please input your username! + Please input your username! - + - Please input your Password! + Please input your Password! @@ -40,19 +40,20 @@ import { `, - styles: [ ` - .login-form { - max-width: 300px; - } + styles: [ + ` + .login-form { + max-width: 300px; + } - .login-form-forgot { - float: right; - } + .login-form-forgot { + float: right; + } - .login-form-button { - width: 100%; - } - ` + .login-form-button { + width: 100%; + } + ` ] }) export class NzDemoFormNormalLoginComponent implements OnInit { @@ -60,19 +61,18 @@ export class NzDemoFormNormalLoginComponent implements OnInit { submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - userName: [ null, [ Validators.required ] ], - password: [ null, [ Validators.required ] ], - remember: [ true ] + userName: [null, [Validators.required]], + password: [null, [Validators.required]], + remember: [true] }); } } diff --git a/components/form/demo/register.ts b/components/form/demo/register.ts index 6cffeedba87..b10ae793b8d 100644 --- a/components/form/demo/register.ts +++ b/components/form/demo/register.ts @@ -1,10 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormControl, - FormGroup, - Validators -} from '@angular/forms'; +import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'nz-demo-form-register', @@ -13,7 +8,7 @@ import { E-mail - + The input is not valid E-mail! @@ -22,15 +17,25 @@ import { Password - - Please input your password! + + Please input your password! Confirm Password - - + + Please confirm your password! @@ -44,12 +49,20 @@ import { Nickname - + - - Please input your nickname! + + Please input your nickname! @@ -62,16 +75,20 @@ import { - + - Please input your phone number! + Please input your phone number! Website - - Please input website! + + Please input website! @@ -79,13 +96,15 @@ import {
- +
- Please input the captcha you got! + Please input the captcha you got! We must make sure that your are a human.
@@ -101,12 +120,15 @@ import {
- `, + + `, styles: [ - `[nz-form] { - max-width: 600px; - }` + ` + [nz-form] { + max-width: 600px; + } + ` ] }) export class NzDemoFormRegisterComponent implements OnInit { @@ -114,8 +136,8 @@ export class NzDemoFormRegisterComponent implements OnInit { submitForm(): void { for (const i in this.validateForm.controls) { - this.validateForm.controls[ i ].markAsDirty(); - this.validateForm.controls[ i ].updateValueAndValidity(); + this.validateForm.controls[i].markAsDirty(); + this.validateForm.controls[i].updateValueAndValidity(); } } @@ -124,33 +146,32 @@ export class NzDemoFormRegisterComponent implements OnInit { Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity()); } - confirmationValidator = (control: FormControl): { [ s: string ]: boolean } => { + confirmationValidator = (control: FormControl): { [s: string]: boolean } => { if (!control.value) { return { required: true }; } else if (control.value !== this.validateForm.controls.password.value) { return { confirm: true, error: true }; } return {}; - } + }; getCaptcha(e: MouseEvent): void { e.preventDefault(); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - email : [ null, [ Validators.email, Validators.required ] ], - password : [ null, [ Validators.required ] ], - checkPassword : [ null, [ Validators.required, this.confirmationValidator ] ], - nickname : [ null, [ Validators.required ] ], - phoneNumberPrefix: [ '+86' ], - phoneNumber : [ null, [ Validators.required ] ], - website : [ null, [ Validators.required ] ], - captcha : [ null, [ Validators.required ] ], - agree : [ false ] + email: [null, [Validators.email, Validators.required]], + password: [null, [Validators.required]], + checkPassword: [null, [Validators.required, this.confirmationValidator]], + nickname: [null, [Validators.required]], + phoneNumberPrefix: ['+86'], + phoneNumber: [null, [Validators.required]], + website: [null, [Validators.required]], + captcha: [null, [Validators.required]], + agree: [false] }); } } diff --git a/components/form/demo/time-related-controls.ts b/components/form/demo/time-related-controls.ts index f0fe99424a6..9335038b2b0 100644 --- a/components/form/demo/time-related-controls.ts +++ b/components/form/demo/time-related-controls.ts @@ -1,8 +1,5 @@ import { Component, OnInit } from '@angular/core'; -import { - FormBuilder, - FormGroup, -} from '@angular/forms'; +import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'nz-demo-form-time-related-controls', @@ -49,12 +46,15 @@ import { - `, - styles : [ ` - form { + + `, + styles: [ + ` + form { max-width: 600px; - } - ` ] + } + ` + ] }) export class NzDemoFormTimeRelatedControlsComponent implements OnInit { validateForm: FormGroup; @@ -63,17 +63,16 @@ export class NzDemoFormTimeRelatedControlsComponent implements OnInit { console.log(this.validateForm.value); } - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - datePicker : [ null ], - datePickerTime : [ null ], - monthPicker : [ null ], - rangePicker : [ [] ], - rangePickerTime: [ [] ], - timePicker : [ null ] + datePicker: [null], + datePickerTime: [null], + monthPicker: [null], + rangePicker: [[]], + rangePickerTime: [[]], + timePicker: [null] }); } } diff --git a/components/form/demo/validate-reactive.ts b/components/form/demo/validate-reactive.ts index ef3fbafdbe5..c5f6cdae0e0 100644 --- a/components/form/demo/validate-reactive.ts +++ b/components/form/demo/validate-reactive.ts @@ -1,12 +1,6 @@ import { Component } from '@angular/core'; -import { - FormBuilder, - FormControl, - FormGroup, - ValidationErrors, - Validators -} from '@angular/forms'; +import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms'; import { Observable, Observer } from 'rxjs'; @Component({ @@ -16,8 +10,13 @@ import { Observable, Observer } from 'rxjs'; Username - - + + Please input your username! @@ -33,8 +32,8 @@ import { Observable, Observer } from 'rxjs'; E-mail - - + + The input is not valid E-mail! @@ -48,16 +47,19 @@ import { Observable, Observer } from 'rxjs'; Password
- - Please input your password! + + Please input your password!
Confirm Password - - + + Please confirm your password! @@ -71,7 +73,10 @@ import { Observable, Observer } from 'rxjs'; Comment - Please write something here! + Please write something here! @@ -80,10 +85,11 @@ import { Observable, Observer } from 'rxjs';
- `, + + `, styles: [ - ` + ` [nz-form] { max-width: 600px; } @@ -99,18 +105,18 @@ export class NzDemoFormValidateReactiveComponent { submitForm = ($event: any, value: any) => { $event.preventDefault(); for (const key in this.validateForm.controls) { - this.validateForm.controls[ key ].markAsDirty(); - this.validateForm.controls[ key ].updateValueAndValidity(); + this.validateForm.controls[key].markAsDirty(); + this.validateForm.controls[key].updateValueAndValidity(); } console.log(value); - } + }; resetForm(e: MouseEvent): void { e.preventDefault(); this.validateForm.reset(); for (const key in this.validateForm.controls) { - this.validateForm.controls[ key ].markAsPristine(); - this.validateForm.controls[ key ].updateValueAndValidity(); + this.validateForm.controls[key].markAsPristine(); + this.validateForm.controls[key].updateValueAndValidity(); } } @@ -118,33 +124,34 @@ export class NzDemoFormValidateReactiveComponent { setTimeout(() => this.validateForm.controls.confirm.updateValueAndValidity()); } - userNameAsyncValidator = (control: FormControl) => Observable.create((observer: Observer) => { - setTimeout(() => { - if (control.value === 'JasonWood') { - observer.next({ error: true, duplicated: true }); - } else { - observer.next(null); - } - observer.complete(); - }, 1000); - }) + userNameAsyncValidator = (control: FormControl) => + Observable.create((observer: Observer) => { + setTimeout(() => { + if (control.value === 'JasonWood') { + observer.next({ error: true, duplicated: true }); + } else { + observer.next(null); + } + observer.complete(); + }, 1000); + }); - confirmValidator = (control: FormControl): { [ s: string ]: boolean } => { + confirmValidator = (control: FormControl): { [s: string]: boolean } => { if (!control.value) { return { required: true }; } else if (control.value !== this.validateForm.controls.password.value) { return { confirm: true, error: true }; } return {}; - } + }; constructor(private fb: FormBuilder) { this.validateForm = this.fb.group({ - userName: [ '', [ Validators.required ], [ this.userNameAsyncValidator ] ], - email : [ '', [ Validators.email, Validators.required ] ], - password: [ '', [ Validators.required ] ], - confirm : [ '', [ this.confirmValidator ] ], - comment : [ '', [ Validators.required ] ] + userName: ['', [Validators.required], [this.userNameAsyncValidator]], + email: ['', [Validators.email, Validators.required]], + password: ['', [Validators.required]], + confirm: ['', [this.confirmValidator]], + comment: ['', [Validators.required]] }); } } diff --git a/components/form/demo/validate-static.ts b/components/form/demo/validate-static.ts index 067eb3d107a..64d2a66a3cb 100644 --- a/components/form/demo/validate-static.ts +++ b/components/form/demo/validate-static.ts @@ -7,40 +7,40 @@ import { Component } from '@angular/core'; Fail - + Should be combination of numbers & alphabets Warning - + Validating - + I'm validating the content Success - + Warning - + Should be combination of numbers & alphabets Fail - + Should be combination of numbers & alphabets @@ -80,17 +80,17 @@ import { Component } from '@angular/core'; - `, - styles : [ + + `, + styles: [ ` [nz-form] { max-width: 600px; } - nz-date-picker ::ng-deep .ant-calendar-picker{ + nz-date-picker ::ng-deep .ant-calendar-picker { width: 100%; } ` ] }) -export class NzDemoFormValidateStaticComponent { -} +export class NzDemoFormValidateStaticComponent {} diff --git a/components/form/nz-form-control.component.ts b/components/form/nz-form-control.component.ts index 209e46de3c4..5987e733268 100644 --- a/components/form/nz-form-control.component.ts +++ b/components/form/nz-form-control.component.ts @@ -1,5 +1,6 @@ import { - AfterContentInit, AfterViewInit, + AfterContentInit, + AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, @@ -9,7 +10,8 @@ import { Input, OnDestroy, OnInit, - Optional, Renderer2, + Optional, + Renderer2, ViewEncapsulation } from '@angular/core'; import { FormControl, FormControlName, NgControl } from '@angular/forms'; @@ -23,21 +25,22 @@ import { NzRowDirective } from '../grid/nz-row.directive'; import { NzFormItemComponent } from './nz-form-item.component'; @Component({ - selector : 'nz-form-control', + selector: 'nz-form-control', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ NzUpdateHostClassService ], - templateUrl : './nz-form-control.component.html', - styles : [ - ` + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [NzUpdateHostClassService], + templateUrl: './nz-form-control.component.html', + styles: [ + ` nz-form-control { display: block; } ` ] }) -export class NzFormControlComponent extends NzColDirective implements OnDestroy, OnInit, AfterContentInit, AfterViewInit, OnDestroy { +export class NzFormControlComponent extends NzColDirective + implements OnDestroy, OnInit, AfterContentInit, AfterViewInit, OnDestroy { private _hasFeedback = false; validateChanges: Subscription | null; validateString: string | null; @@ -84,9 +87,7 @@ export class NzFormControlComponent extends NzColDirective implements OnDestroy, this.removeSubscribe(); /** miss detect https://github.com/angular/angular/issues/10887 **/ if (this.validateControl && this.validateControl.statusChanges) { - this.validateChanges = this.validateControl.statusChanges.pipe( - startWith(null) - ).subscribe(() => { + this.validateChanges = this.validateControl.statusChanges.pipe(startWith(null)).subscribe(() => { this.setControlClassMap(); this.cdr.markForCheck(); }); @@ -94,34 +95,46 @@ export class NzFormControlComponent extends NzColDirective implements OnDestroy, } validateControlStatus(status: string): boolean { - return !!this.validateControl - && (this.validateControl.dirty || this.validateControl.touched) - && (this.validateControl.status === status); + return ( + !!this.validateControl && + (this.validateControl.dirty || this.validateControl.touched) && + this.validateControl.status === status + ); } setControlClassMap(): void { this.controlClassMap = { - [ `has-warning` ] : this.validateString === 'warning', - [ `is-validating` ]: this.validateString === 'validating' || this.validateString === 'pending' || this.validateControlStatus('PENDING'), - [ `has-error` ] : this.validateString === 'error' || this.validateControlStatus('INVALID'), - [ `has-success` ] : this.validateString === 'success' || this.validateControlStatus('VALID'), - [ `has-feedback` ] : this.nzHasFeedback + [`has-warning`]: this.validateString === 'warning', + [`is-validating`]: + this.validateString === 'validating' || + this.validateString === 'pending' || + this.validateControlStatus('PENDING'), + [`has-error`]: this.validateString === 'error' || this.validateControlStatus('INVALID'), + [`has-success`]: this.validateString === 'success' || this.validateControlStatus('VALID'), + [`has-feedback`]: this.nzHasFeedback }; - if (this.controlClassMap[ 'has-warning' ]) { + if (this.controlClassMap['has-warning']) { this.iconType = 'exclamation-circle-fill'; - } else if (this.controlClassMap[ 'is-validating' ]) { + } else if (this.controlClassMap['is-validating']) { this.iconType = 'loading'; - } else if (this.controlClassMap[ 'has-error' ]) { + } else if (this.controlClassMap['has-error']) { this.iconType = 'close-circle-fill'; - } else if (this.controlClassMap[ 'has-success' ]) { + } else if (this.controlClassMap['has-success']) { this.iconType = 'check-circle-fill'; } else { this.iconType = ''; } } - constructor(nzUpdateHostClassService: NzUpdateHostClassService, elementRef: ElementRef, @Optional() @Host() nzFormItemComponent: NzFormItemComponent, @Optional() @Host() nzRowDirective: NzRowDirective, private cdr: ChangeDetectorRef, renderer: Renderer2) { + constructor( + nzUpdateHostClassService: NzUpdateHostClassService, + elementRef: ElementRef, + @Optional() @Host() nzFormItemComponent: NzFormItemComponent, + @Optional() @Host() nzRowDirective: NzRowDirective, + private cdr: ChangeDetectorRef, + renderer: Renderer2 + ) { super(nzUpdateHostClassService, elementRef, nzFormItemComponent || nzRowDirective, renderer); renderer.addClass(elementRef.nativeElement, 'ant-form-item-control-wrapper'); } @@ -137,7 +150,7 @@ export class NzFormControlComponent extends NzColDirective implements OnDestroy, } ngAfterContentInit(): void { - if (this.defaultValidateControl && (!this.validateControl) && (!this.validateString)) { + if (this.defaultValidateControl && !this.validateControl && !this.validateString) { this.nzValidateStatus = this.defaultValidateControl; } } diff --git a/components/form/nz-form-control.spec.ts b/components/form/nz-form-control.spec.ts index 0efea7f678a..8089edb0d74 100644 --- a/components/form/nz-form-control.spec.ts +++ b/components/form/nz-form-control.spec.ts @@ -17,8 +17,12 @@ import { NzFormModule } from './nz-form.module'; describe('nz-form-control', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzFormModule, NoopAnimationsModule, ReactiveFormsModule, FormsModule ], - declarations: [ NzTestStaticFormControlComponent, NzTestReactiveFormControlComponent, NzTestReactiveFormControlInitStatusComponent ] + imports: [NzFormModule, NoopAnimationsModule, ReactiveFormsModule, FormsModule], + declarations: [ + NzTestStaticFormControlComponent, + NzTestReactiveFormControlComponent, + NzTestReactiveFormControlInitStatusComponent + ] }); TestBed.compileComponents(); })); @@ -45,18 +49,20 @@ describe('nz-form-control', () => { }); it('should status work', () => { fixture.detectChanges(); - const statusList = [ 'warning', 'validating', 'pending', 'error', 'success' ]; - const statusMap: { [ key: string ]: string } = { - 'warning' : 'has-warning', - 'validating': 'is-validating', - 'pending' : 'is-validating', - 'error' : 'has-error', - 'success' : 'has-success' + const statusList = ['warning', 'validating', 'pending', 'error', 'success']; + const statusMap: { [key: string]: string } = { + warning: 'has-warning', + validating: 'is-validating', + pending: 'is-validating', + error: 'has-error', + success: 'has-success' }; statusList.forEach(status => { testComponent.status = status; fixture.detectChanges(); - expect(formControl.nativeElement.querySelector('.ant-form-item-control').classList).toContain(statusMap[ status ]); + expect(formControl.nativeElement.querySelector('.ant-form-item-control').classList).toContain( + statusMap[status] + ); }); }); }); @@ -74,8 +80,12 @@ describe('nz-form-control', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(formControls[ 0 ].nativeElement.querySelector('.ant-form-item-control').className).toBe('ant-form-item-control'); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').className).toBe('ant-form-item-control'); + expect(formControls[0].nativeElement.querySelector('.ant-form-item-control').className).toBe( + 'ant-form-item-control' + ); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').className).toBe( + 'ant-form-item-control' + ); })); it('should valid work', fakeAsync(() => { testComponent.formGroup.get('input')!.markAsDirty(); @@ -92,8 +102,8 @@ describe('nz-form-control', () => { fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(formControls[ 0 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-success'); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-success'); + expect(formControls[0].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-success'); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-success'); })); it('should invalid work', fakeAsync(() => { testComponent.formGroup.get('input')!.markAsDirty(); @@ -108,8 +118,8 @@ describe('nz-form-control', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(formControls[ 0 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); + expect(formControls[0].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); })); it('should dirty work', fakeAsync(() => { testComponent.formGroup.get('input')!.markAsDirty(); @@ -122,8 +132,8 @@ describe('nz-form-control', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(formControls[ 0 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); + expect(formControls[0].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); testComponent.formGroup.get('input')!.markAsPristine(); testComponent.formGroup.get('input2')!.markAsPristine(); fixture.detectChanges(); @@ -134,8 +144,12 @@ describe('nz-form-control', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(formControls[ 0 ].nativeElement.querySelector('.ant-form-item-control').classList).not.toContain('has-error'); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').classList).not.toContain('has-error'); + expect(formControls[0].nativeElement.querySelector('.ant-form-item-control').classList).not.toContain( + 'has-error' + ); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').classList).not.toContain( + 'has-error' + ); })); it('should pending work', fakeAsync(() => { testComponent.formGroup.get('input2')!.markAsDirty(); @@ -146,7 +160,7 @@ describe('nz-form-control', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(formControls[ 1 ].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); + expect(formControls[1].nativeElement.querySelector('.ant-form-item-control').classList).toContain('has-error'); })); }); describe('reactive init status', () => { @@ -168,7 +182,8 @@ describe('nz-form-control', () => { @Component({ template: ` - ` + + ` }) export class NzTestStaticFormControlComponent { hasFeedback = false; @@ -179,12 +194,12 @@ export class NzTestStaticFormControlComponent { template: `
- + - + - +
` }) @@ -194,9 +209,9 @@ export class NzTestReactiveFormControlComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - input : [ '', [ Validators.required ] ], - input2: [ '', [ Validators.required ] ], - input3: [ '', [ Validators.required ] ] + input: ['', [Validators.required]], + input2: ['', [Validators.required]], + input3: ['', [Validators.required]] }); this.validateStatus = this.formGroup.get('input2') as FormControl; } @@ -207,7 +222,7 @@ export class NzTestReactiveFormControlComponent { template: `
- +
` @@ -217,7 +232,7 @@ export class NzTestReactiveFormControlInitStatusComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - input: [ '', [ Validators.required ] ] + input: ['', [Validators.required]] }); this.formGroup.controls.input.markAsDirty(); } diff --git a/components/form/nz-form-explain.component.ts b/components/form/nz-form-explain.component.ts index c7953b0e061..fe65352cb00 100644 --- a/components/form/nz-form-explain.component.ts +++ b/components/form/nz-form-explain.component.ts @@ -2,16 +2,18 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsul import { helpMotion } from '../core/animation/help'; @Component({ - selector : 'nz-form-explain', + selector: 'nz-form-explain', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - animations : [ helpMotion ], - templateUrl : './nz-form-explain.component.html', - styles : [ - `nz-form-explain { - display: block; - }` + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + animations: [helpMotion], + templateUrl: './nz-form-explain.component.html', + styles: [ + ` + nz-form-explain { + display: block; + } + ` ] }) export class NzFormExplainComponent { diff --git a/components/form/nz-form-extra.component.ts b/components/form/nz-form-extra.component.ts index 9a05cbb1f37..8e8e03741cf 100644 --- a/components/form/nz-form-extra.component.ts +++ b/components/form/nz-form-extra.component.ts @@ -1,13 +1,13 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-form-extra', - templateUrl : './nz-form-extra.component.html', + selector: 'nz-form-extra', + templateUrl: './nz-form-extra.component.html', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - styles : [ - ` + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + styles: [ + ` nz-form-extra { display: block; } diff --git a/components/form/nz-form-item.component.ts b/components/form/nz-form-item.component.ts index 00280298f6b..80294cce2dc 100644 --- a/components/form/nz-form-item.component.ts +++ b/components/form/nz-form-item.component.ts @@ -22,17 +22,17 @@ import { NzFormExplainComponent } from './nz-form-explain.component'; /** should add nz-row directive to host, track https://github.com/angular/angular/issues/8785 **/ @Component({ - selector : 'nz-form-item', + selector: 'nz-form-item', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - providers : [ NzUpdateHostClassService ], - templateUrl : './nz-form-item.component.html', - host : { + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + providers: [NzUpdateHostClassService], + templateUrl: './nz-form-item.component.html', + host: { '[class.ant-form-item-with-help]': 'listOfNzFormExplainComponent && (listOfNzFormExplainComponent.length>0)' }, - styles : [ - ` + styles: [ + ` nz-form-item { display: block; } @@ -41,7 +41,9 @@ import { NzFormExplainComponent } from './nz-form-explain.component'; }) export class NzFormItemComponent extends NzRowDirective implements AfterContentInit, OnDestroy { private _flex = false; - @ContentChildren(NzFormExplainComponent, { descendants: true }) listOfNzFormExplainComponent: QueryList; + @ContentChildren(NzFormExplainComponent, { descendants: true }) listOfNzFormExplainComponent: QueryList< + NzFormExplainComponent + >; @Input() set nzFlex(value: boolean) { @@ -53,7 +55,15 @@ export class NzFormItemComponent extends NzRowDirective implements AfterContentI } } - constructor(elementRef: ElementRef, renderer: Renderer2, nzUpdateHostClassService: NzUpdateHostClassService, mediaMatcher: MediaMatcher, ngZone: NgZone, platform: Platform, private cdr: ChangeDetectorRef) { + constructor( + elementRef: ElementRef, + renderer: Renderer2, + nzUpdateHostClassService: NzUpdateHostClassService, + mediaMatcher: MediaMatcher, + ngZone: NgZone, + platform: Platform, + private cdr: ChangeDetectorRef + ) { super(elementRef, renderer, nzUpdateHostClassService, mediaMatcher, ngZone, platform); renderer.addClass(elementRef.nativeElement, 'ant-form-item'); } diff --git a/components/form/nz-form-item.spec.ts b/components/form/nz-form-item.spec.ts index 2d10d9583a6..96641774e22 100644 --- a/components/form/nz-form-item.spec.ts +++ b/components/form/nz-form-item.spec.ts @@ -9,8 +9,8 @@ import { NzFormModule } from './nz-form.module'; describe('nz-form-item', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzFormModule, NoopAnimationsModule ], - declarations: [ NzTestFormItemComponent ] + imports: [NzFormModule, NoopAnimationsModule], + declarations: [NzTestFormItemComponent] }); TestBed.compileComponents(); })); @@ -60,7 +60,8 @@ describe('nz-form-item', () => { - ` + + ` }) export class NzTestFormItemComponent { first = true; diff --git a/components/form/nz-form-label.component.ts b/components/form/nz-form-label.component.ts index a8127d04cf3..4d6168bda4c 100644 --- a/components/form/nz-form-label.component.ts +++ b/components/form/nz-form-label.component.ts @@ -4,8 +4,10 @@ import { Component, ElementRef, Host, - Input, OnDestroy, - Optional, Renderer2, + Input, + OnDestroy, + Optional, + Renderer2, ViewEncapsulation } from '@angular/core'; import { NzUpdateHostClassService } from '../core/services/update-host-class.service'; @@ -15,18 +17,24 @@ import { NzRowDirective } from '../grid/nz-row.directive'; import { NzFormItemComponent } from './nz-form-item.component'; @Component({ - selector : 'nz-form-label', - providers : [ NzUpdateHostClassService ], + selector: 'nz-form-label', + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-form-label.component.html' + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-form-label.component.html' }) export class NzFormLabelComponent extends NzColDirective implements OnDestroy, AfterViewInit { @Input() nzFor: string; @Input() @InputBoolean() nzRequired = false; - constructor(nzUpdateHostClassService: NzUpdateHostClassService, elementRef: ElementRef, @Optional() @Host() nzFormItemComponent: NzFormItemComponent, @Optional() @Host() nzRowDirective: NzRowDirective, renderer: Renderer2) { + constructor( + nzUpdateHostClassService: NzUpdateHostClassService, + elementRef: ElementRef, + @Optional() @Host() nzFormItemComponent: NzFormItemComponent, + @Optional() @Host() nzRowDirective: NzRowDirective, + renderer: Renderer2 + ) { super(nzUpdateHostClassService, elementRef, nzFormItemComponent || nzRowDirective, renderer); renderer.addClass(elementRef.nativeElement, 'ant-form-item-label'); } diff --git a/components/form/nz-form-label.spec.ts b/components/form/nz-form-label.spec.ts index 635be163b7a..e3bfa991edf 100644 --- a/components/form/nz-form-label.spec.ts +++ b/components/form/nz-form-label.spec.ts @@ -7,8 +7,8 @@ import { NzFormLabelComponent } from './nz-form-label.component'; describe('nz-form-label', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule ], - declarations: [ NzFormLabelComponent, NzTestFormLabelComponent ] + imports: [NoopAnimationsModule], + declarations: [NzFormLabelComponent, NzTestFormLabelComponent] }); TestBed.compileComponents(); })); @@ -42,7 +42,8 @@ describe('nz-form-label', () => { @Component({ template: ` - ` + + ` }) export class NzTestFormLabelComponent { forValue = 'test'; diff --git a/components/form/nz-form-split.component.ts b/components/form/nz-form-split.component.ts index e36ae85fc0e..d927c515636 100644 --- a/components/form/nz-form-split.component.ts +++ b/components/form/nz-form-split.component.ts @@ -1,11 +1,11 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-form-split', + selector: 'nz-form-split', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-form-split.component.html' + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-form-split.component.html' }) export class NzFormSplitComponent { constructor(public elementRef: ElementRef, private renderer: Renderer2) { diff --git a/components/form/nz-form-split.spec.ts b/components/form/nz-form-split.spec.ts index 530da0d8e6d..c058caeb6dc 100644 --- a/components/form/nz-form-split.spec.ts +++ b/components/form/nz-form-split.spec.ts @@ -7,8 +7,8 @@ import { NzFormSplitComponent } from './nz-form-split.component'; describe('nz-form-split', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule ], - declarations: [ NzFormSplitComponent, NzTestFormSplitComponent ] + imports: [NoopAnimationsModule], + declarations: [NzFormSplitComponent, NzTestFormSplitComponent] }); TestBed.compileComponents(); })); @@ -28,7 +28,8 @@ describe('nz-form-split', () => { }); @Component({ - template: `` + template: ` + + ` }) -export class NzTestFormSplitComponent { -} +export class NzTestFormSplitComponent {} diff --git a/components/form/nz-form-text.component.ts b/components/form/nz-form-text.component.ts index eaa602ae6b9..bdfa65b824e 100644 --- a/components/form/nz-form-text.component.ts +++ b/components/form/nz-form-text.component.ts @@ -1,11 +1,11 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-form-text', + selector: 'nz-form-text', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-form-text.component.html' + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-form-text.component.html' }) export class NzFormTextComponent { constructor(public elementRef: ElementRef, private renderer: Renderer2) { diff --git a/components/form/nz-form-text.spec.ts b/components/form/nz-form-text.spec.ts index a9acf2b2d9d..6c52ba51e6d 100644 --- a/components/form/nz-form-text.spec.ts +++ b/components/form/nz-form-text.spec.ts @@ -7,8 +7,8 @@ import { NzFormTextComponent } from './nz-form-text.component'; describe('nz-form-text', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule ], - declarations: [ NzFormTextComponent, NzTestFormTextComponent ] + imports: [NoopAnimationsModule], + declarations: [NzFormTextComponent, NzTestFormTextComponent] }); TestBed.compileComponents(); })); @@ -28,7 +28,8 @@ describe('nz-form-text', () => { }); @Component({ - template: `` + template: ` + + ` }) -export class NzTestFormTextComponent { -} +export class NzTestFormTextComponent {} diff --git a/components/form/nz-form.directive.ts b/components/form/nz-form.directive.ts index e59acadfd7f..d09a924b9eb 100644 --- a/components/form/nz-form.directive.ts +++ b/components/form/nz-form.directive.ts @@ -2,19 +2,23 @@ import { Directive, ElementRef, Input, OnChanges, OnInit, Renderer2 } from '@ang import { NzUpdateHostClassService } from '../core/services/update-host-class.service'; @Directive({ - selector : '[nz-form]', - providers: [ NzUpdateHostClassService ] + selector: '[nz-form]', + providers: [NzUpdateHostClassService] }) export class NzFormDirective implements OnInit, OnChanges { @Input() nzLayout = 'horizontal'; setClassMap(): void { this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ `ant-form-${this.nzLayout}` ]: this.nzLayout + [`ant-form-${this.nzLayout}`]: this.nzLayout }); } - constructor(private elementRef: ElementRef, private renderer: Renderer2, private nzUpdateHostClassService: NzUpdateHostClassService) { + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + private nzUpdateHostClassService: NzUpdateHostClassService + ) { this.renderer.addClass(elementRef.nativeElement, 'ant-form'); } diff --git a/components/form/nz-form.module.ts b/components/form/nz-form.module.ts index 0cd0e9374d8..8720fdc6471 100644 --- a/components/form/nz-form.module.ts +++ b/components/form/nz-form.module.ts @@ -23,8 +23,9 @@ import { NzFormDirective } from './nz-form.directive'; NzFormControlComponent, NzFormExplainComponent, NzFormTextComponent, - NzFormSplitComponent ], - exports : [ + NzFormSplitComponent + ], + exports: [ NzFormExtraComponent, NzFormLabelComponent, NzFormDirective, @@ -34,7 +35,6 @@ import { NzFormDirective } from './nz-form.directive'; NzFormTextComponent, NzFormSplitComponent ], - imports : [ CommonModule, NzGridModule, NzIconModule, LayoutModule, PlatformModule ] + imports: [CommonModule, NzGridModule, NzIconModule, LayoutModule, PlatformModule] }) -export class NzFormModule { -} +export class NzFormModule {} diff --git a/components/form/nz-form.spec.ts b/components/form/nz-form.spec.ts index 4f99cfcc30b..4db76c0a562 100644 --- a/components/form/nz-form.spec.ts +++ b/components/form/nz-form.spec.ts @@ -7,8 +7,8 @@ import { NzFormDirective } from './nz-form.directive'; describe('nz-form', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule ], - declarations: [ NzFormDirective, NzTestFormDirectiveComponent ] + imports: [NoopAnimationsModule], + declarations: [NzFormDirective, NzTestFormDirectiveComponent] }); TestBed.compileComponents(); })); @@ -44,7 +44,8 @@ describe('nz-form', () => { @Component({ template: ` -
` +
+ ` }) export class NzTestFormDirectiveComponent { layout = 'horizontal'; diff --git a/components/grid/demo/basic.ts b/components/grid/demo/basic.ts index ece802c5430..8fab92e1bfa 100755 --- a/components/grid/demo/basic.ts +++ b/components/grid/demo/basic.ts @@ -17,7 +17,7 @@ import { Component } from '@angular/core';
col-6
col-6
col-6
- ` + + ` }) -export class NzDemoGridBasicComponent { -} +export class NzDemoGridBasicComponent {} diff --git a/components/grid/demo/flex-align.ts b/components/grid/demo/flex-align.ts index 00506767552..770588182bb 100755 --- a/components/grid/demo/flex-align.ts +++ b/components/grid/demo/flex-align.ts @@ -25,8 +25,8 @@ import { Component } from '@angular/core';

col-4

col-4

- `, - styles : [] + + `, + styles: [] }) -export class NzDemoGridFlexAlignComponent { -} +export class NzDemoGridFlexAlignComponent {} diff --git a/components/grid/demo/flex-order.ts b/components/grid/demo/flex-order.ts index 766eaf8509e..9fc33fe45ba 100755 --- a/components/grid/demo/flex-order.ts +++ b/components/grid/demo/flex-order.ts @@ -4,19 +4,19 @@ import { Component, OnInit } from '@angular/core'; selector: 'nz-demo-grid-flex-order', template: `
-
+
{{ i + 1 }} col-order-{{ order }}
`, - styles : [] + styles: [] }) export class NzDemoGridFlexOrderComponent implements OnInit { - orderList = [ 1, 2, 3, 4 ]; + orderList = [1, 2, 3, 4]; ngOnInit(): void { setTimeout(() => { - this.orderList = [ ...this.orderList.reverse() ]; + this.orderList = [...this.orderList.reverse()]; }, 10000); } } diff --git a/components/grid/demo/flex.ts b/components/grid/demo/flex.ts index 675f77a9ffd..78648b80fbc 100755 --- a/components/grid/demo/flex.ts +++ b/components/grid/demo/flex.ts @@ -39,7 +39,7 @@ import { Component } from '@angular/core';
col-4
col-4
- ` + + ` }) -export class NzDemoGridFlexComponent { -} +export class NzDemoGridFlexComponent {} diff --git a/components/grid/demo/gutter.ts b/components/grid/demo/gutter.ts index 62b4b305402..e89abcd36d4 100755 --- a/components/grid/demo/gutter.ts +++ b/components/grid/demo/gutter.ts @@ -36,14 +36,13 @@ import { Component } from '@angular/core'; `, - styles : [ + styles: [ ` .gutter-box { - background: #00A0E9; + background: #00a0e9; padding: 5px 0; } ` ] }) -export class NzDemoGridGutterComponent { -} +export class NzDemoGridGutterComponent {} diff --git a/components/grid/demo/offset.ts b/components/grid/demo/offset.ts index c1cfa0980f5..b3b4747396a 100755 --- a/components/grid/demo/offset.ts +++ b/components/grid/demo/offset.ts @@ -25,7 +25,6 @@ import { Component } from '@angular/core'; `, - styles : [] + styles: [] }) -export class NzDemoGridOffsetComponent { -} +export class NzDemoGridOffsetComponent {} diff --git a/components/grid/demo/playground.ts b/components/grid/demo/playground.ts index 65a0555ea37..374b64fe355 100755 --- a/components/grid/demo/playground.ts +++ b/components/grid/demo/playground.ts @@ -6,26 +6,38 @@ import { Component } from '@angular/core';
Gutter (px):
- +
Column Count:
- +
-
+
Column
`, - styles : [ - ` + styles: [ + ` .grid-config { - background: #00A0E9; + background: #00a0e9; height: 120px; line-height: 120px; font-size: 13px; @@ -37,7 +49,7 @@ export class NzDemoGridPlaygroundComponent { gutter = 16; count = 4; marksGutter = { - 8 : 8, + 8: 8, 16: 16, 24: 24, 32: 32, @@ -45,11 +57,11 @@ export class NzDemoGridPlaygroundComponent { 48: 48 }; marksCount = { - 2 : 2, - 3 : 3, - 4 : 4, - 6 : 6, - 8 : 8, + 2: 2, + 3: 3, + 4: 4, + 6: 6, + 8: 8, 12: 12 }; diff --git a/components/grid/demo/responsive-more.ts b/components/grid/demo/responsive-more.ts index 664bfa26f87..a0654c7b74a 100755 --- a/components/grid/demo/responsive-more.ts +++ b/components/grid/demo/responsive-more.ts @@ -13,8 +13,8 @@ import { Component } from '@angular/core';
Col
-
`, - styles : [] + + `, + styles: [] }) -export class NzDemoGridResponsiveMoreComponent { -} +export class NzDemoGridResponsiveMoreComponent {} diff --git a/components/grid/demo/responsive.ts b/components/grid/demo/responsive.ts index 7b4304fe2f3..3cdf68cd0d3 100755 --- a/components/grid/demo/responsive.ts +++ b/components/grid/demo/responsive.ts @@ -13,8 +13,8 @@ import { Component } from '@angular/core';
Col
- `, - styles : [] + + `, + styles: [] }) -export class NzDemoGridResponsiveComponent { -} +export class NzDemoGridResponsiveComponent {} diff --git a/components/grid/demo/sort.ts b/components/grid/demo/sort.ts index c9a5d15a70c..00686b45752 100755 --- a/components/grid/demo/sort.ts +++ b/components/grid/demo/sort.ts @@ -12,7 +12,6 @@ import { Component } from '@angular/core'; `, - styles : [] + styles: [] }) -export class NzDemoGridSortComponent { -} +export class NzDemoGridSortComponent {} diff --git a/components/grid/nz-col.directive.ts b/components/grid/nz-col.directive.ts index 4a35323b888..a85fd08aa39 100644 --- a/components/grid/nz-col.directive.ts +++ b/components/grid/nz-col.directive.ts @@ -28,8 +28,8 @@ export interface EmbeddedProperty { } @Directive({ - selector : '[nz-col],nz-col', - providers: [ NzUpdateHostClassService ] + selector: '[nz-col],nz-col', + providers: [NzUpdateHostClassService] }) export class NzColDirective implements OnInit, OnChanges, AfterViewInit, OnDestroy { private el: HTMLElement = this.elementRef.nativeElement; @@ -48,48 +48,51 @@ export class NzColDirective implements OnInit, OnChanges, AfterViewInit, OnDestr @Input() nzXl: number | EmbeddedProperty; @Input() nzXXl: number | EmbeddedProperty; - [ property: string ]: any // tslint:disable-line:no-any + [property: string]: any; // tslint:disable-line:no-any /** temp solution since no method add classMap to host https://github.com/angular/angular/issues/7289*/ setClassMap(): void { const classMap = { - [ `${this.prefixCls}-${this.nzSpan}` ] : isNotNil(this.nzSpan), - [ `${this.prefixCls}-order-${this.nzOrder}` ] : isNotNil(this.nzOrder), - [ `${this.prefixCls}-offset-${this.nzOffset}` ]: isNotNil(this.nzOffset), - [ `${this.prefixCls}-pull-${this.nzPull}` ] : isNotNil(this.nzPull), - [ `${this.prefixCls}-push-${this.nzPush}` ] : isNotNil(this.nzPush), + [`${this.prefixCls}-${this.nzSpan}`]: isNotNil(this.nzSpan), + [`${this.prefixCls}-order-${this.nzOrder}`]: isNotNil(this.nzOrder), + [`${this.prefixCls}-offset-${this.nzOffset}`]: isNotNil(this.nzOffset), + [`${this.prefixCls}-pull-${this.nzPull}`]: isNotNil(this.nzPull), + [`${this.prefixCls}-push-${this.nzPush}`]: isNotNil(this.nzPush), ...this.generateClass() }; this.nzUpdateHostClassService.updateHostClass(this.el, classMap); } generateClass(): object { - const listOfSizeInputName = [ 'nzXs', 'nzSm', 'nzMd', 'nzLg', 'nzXl', 'nzXXl' ]; + const listOfSizeInputName = ['nzXs', 'nzSm', 'nzMd', 'nzLg', 'nzXl', 'nzXXl']; const listClassMap: NgClassInterface = {}; listOfSizeInputName.forEach(name => { const sizeName = name.replace('nz', '').toLowerCase(); - if (isNotNil(this[ name ])) { - if ((typeof (this[ name ]) === 'number') || (typeof (this[ name ]) === 'string')) { - listClassMap[ `${this.prefixCls}-${sizeName}-${this[ name ]}` ] = true; + if (isNotNil(this[name])) { + if (typeof this[name] === 'number' || typeof this[name] === 'string') { + listClassMap[`${this.prefixCls}-${sizeName}-${this[name]}`] = true; } else { - listClassMap[ `${this.prefixCls}-${sizeName}-${this[ name ].span}` ] = this[ name ] && isNotNil(this[ name ].span); - listClassMap[ `${this.prefixCls}-${sizeName}-pull-${this[ name ].pull}` ] = this[ name ] && isNotNil(this[ name ].pull); - listClassMap[ `${this.prefixCls}-${sizeName}-push-${this[ name ].push}` ] = this[ name ] && isNotNil(this[ name ].push); - listClassMap[ `${this.prefixCls}-${sizeName}-offset-${this[ name ].offset}` ] = this[ name ] && isNotNil(this[ name ].offset); - listClassMap[ `${this.prefixCls}-${sizeName}-order-${this[ name ].order}` ] = this[ name ] && isNotNil(this[ name ].order); + listClassMap[`${this.prefixCls}-${sizeName}-${this[name].span}`] = this[name] && isNotNil(this[name].span); + listClassMap[`${this.prefixCls}-${sizeName}-pull-${this[name].pull}`] = + this[name] && isNotNil(this[name].pull); + listClassMap[`${this.prefixCls}-${sizeName}-push-${this[name].push}`] = + this[name] && isNotNil(this[name].push); + listClassMap[`${this.prefixCls}-${sizeName}-offset-${this[name].offset}`] = + this[name] && isNotNil(this[name].offset); + listClassMap[`${this.prefixCls}-${sizeName}-order-${this[name].order}`] = + this[name] && isNotNil(this[name].order); } } - }); return listClassMap; } - constructor(private nzUpdateHostClassService: NzUpdateHostClassService, - private elementRef: ElementRef, - @Optional() @Host() public nzRowDirective: NzRowDirective, - public renderer: Renderer2 - ) { - } + constructor( + private nzUpdateHostClassService: NzUpdateHostClassService, + private elementRef: ElementRef, + @Optional() @Host() public nzRowDirective: NzRowDirective, + public renderer: Renderer2 + ) {} ngOnChanges(): void { this.setClassMap(); @@ -97,13 +100,15 @@ export class NzColDirective implements OnInit, OnChanges, AfterViewInit, OnDestr ngAfterViewInit(): void { if (this.nzRowDirective) { - this.nzRowDirective.actualGutter$.pipe( - startWith(this.nzRowDirective.actualGutter), - takeUntil(this.destroy$) - ).subscribe((actualGutter) => { - this.renderer.setStyle(this.el, 'padding-left', `${actualGutter / 2}px`); - this.renderer.setStyle(this.el, 'padding-right', `${actualGutter / 2}px`); - }); + this.nzRowDirective.actualGutter$ + .pipe( + startWith(this.nzRowDirective.actualGutter), + takeUntil(this.destroy$) + ) + .subscribe(actualGutter => { + this.renderer.setStyle(this.el, 'padding-left', `${actualGutter / 2}px`); + this.renderer.setStyle(this.el, 'padding-right', `${actualGutter / 2}px`); + }); } } diff --git a/components/grid/nz-grid.module.ts b/components/grid/nz-grid.module.ts index fee889e97e4..da77de1a60c 100644 --- a/components/grid/nz-grid.module.ts +++ b/components/grid/nz-grid.module.ts @@ -7,9 +7,8 @@ import { NzColDirective } from './nz-col.directive'; import { NzRowDirective } from './nz-row.directive'; @NgModule({ - declarations: [ NzColDirective, NzRowDirective ], - exports : [ NzColDirective, NzRowDirective ], - imports : [ CommonModule, LayoutModule, PlatformModule ] + declarations: [NzColDirective, NzRowDirective], + exports: [NzColDirective, NzRowDirective], + imports: [CommonModule, LayoutModule, PlatformModule] }) -export class NzGridModule { -} +export class NzGridModule {} diff --git a/components/grid/nz-grid.spec.ts b/components/grid/nz-grid.spec.ts index 92f404d7a30..fd46c17d36d 100644 --- a/components/grid/nz-grid.spec.ts +++ b/components/grid/nz-grid.spec.ts @@ -24,9 +24,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridBasicComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridBasicComponent], + providers: [] }).compileComponents(); })); @@ -39,15 +39,15 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); expect(rows.every(row => row.nativeElement.classList.contains('ant-row'))).toBe(true); - expect(cols[ 0 ].nativeElement.classList.contains('ant-col-12')).toBe(true); - expect(cols[ 1 ].nativeElement.classList.contains('ant-col-12')).toBe(true); - expect(cols[ 2 ].nativeElement.classList.contains('ant-col-8')).toBe(true); - expect(cols[ 3 ].nativeElement.classList.contains('ant-col-8')).toBe(true); - expect(cols[ 4 ].nativeElement.classList.contains('ant-col-8')).toBe(true); - expect(cols[ 5 ].nativeElement.classList.contains('ant-col-6')).toBe(true); - expect(cols[ 6 ].nativeElement.classList.contains('ant-col-6')).toBe(true); - expect(cols[ 7 ].nativeElement.classList.contains('ant-col-6')).toBe(true); - expect(cols[ 8 ].nativeElement.classList.contains('ant-col-6')).toBe(true); + expect(cols[0].nativeElement.classList.contains('ant-col-12')).toBe(true); + expect(cols[1].nativeElement.classList.contains('ant-col-12')).toBe(true); + expect(cols[2].nativeElement.classList.contains('ant-col-8')).toBe(true); + expect(cols[3].nativeElement.classList.contains('ant-col-8')).toBe(true); + expect(cols[4].nativeElement.classList.contains('ant-col-8')).toBe(true); + expect(cols[5].nativeElement.classList.contains('ant-col-6')).toBe(true); + expect(cols[6].nativeElement.classList.contains('ant-col-6')).toBe(true); + expect(cols[7].nativeElement.classList.contains('ant-col-6')).toBe(true); + expect(cols[8].nativeElement.classList.contains('ant-col-6')).toBe(true); }); }); describe('flex', () => { @@ -57,9 +57,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridFlexComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridFlexComponent], + providers: [] }).compileComponents(); })); @@ -71,11 +71,11 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(rows[ 0 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-start'); - expect(rows[ 1 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-center'); - expect(rows[ 2 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-end'); - expect(rows[ 3 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-space-between'); - expect(rows[ 4 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-space-around'); + expect(rows[0].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-start'); + expect(rows[1].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-center'); + expect(rows[2].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-end'); + expect(rows[3].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-space-between'); + expect(rows[4].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-space-around'); expect(cols.every(col => col.nativeElement.classList.contains('ant-col-4'))).toBe(true); }); }); @@ -87,9 +87,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridFlexAlignComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridFlexAlignComponent], + providers: [] }).compileComponents(); })); @@ -101,9 +101,9 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(rows[ 0 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-center'); - expect(rows[ 1 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-middle ant-row-flex-space-around'); - expect(rows[ 2 ].nativeElement.className).toBe('ant-row-flex ant-row-flex-bottom ant-row-flex-space-between'); + expect(rows[0].nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-center'); + expect(rows[1].nativeElement.className).toBe('ant-row-flex ant-row-flex-middle ant-row-flex-space-around'); + expect(rows[2].nativeElement.className).toBe('ant-row-flex ant-row-flex-bottom ant-row-flex-space-between'); expect(cols.every(col => col.nativeElement.classList.contains('ant-col-4'))).toBe(true); }); }); @@ -114,9 +114,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridFlexOrderComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridFlexOrderComponent], + providers: [] }).compileComponents(); })); @@ -129,18 +129,18 @@ describe('grid', () => { fixture.detectChanges(); let cols = fixture.debugElement.queryAll(By.directive(NzColDirective)); expect(row.nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-start'); - expect(cols[ 0 ].nativeElement.classList.contains('ant-col-order-1')).toBe(true); - expect(cols[ 1 ].nativeElement.classList.contains('ant-col-order-2')).toBe(true); - expect(cols[ 2 ].nativeElement.classList.contains('ant-col-order-3')).toBe(true); - expect(cols[ 3 ].nativeElement.classList.contains('ant-col-order-4')).toBe(true); + expect(cols[0].nativeElement.classList.contains('ant-col-order-1')).toBe(true); + expect(cols[1].nativeElement.classList.contains('ant-col-order-2')).toBe(true); + expect(cols[2].nativeElement.classList.contains('ant-col-order-3')).toBe(true); + expect(cols[3].nativeElement.classList.contains('ant-col-order-4')).toBe(true); tick(10000); fixture.detectChanges(); cols = fixture.debugElement.queryAll(By.directive(NzColDirective)); expect(row.nativeElement.className).toBe('ant-row-flex ant-row-flex-top ant-row-flex-start'); - expect(cols[ 0 ].nativeElement.classList.contains('ant-col-order-4')).toBe(true); - expect(cols[ 1 ].nativeElement.classList.contains('ant-col-order-3')).toBe(true); - expect(cols[ 2 ].nativeElement.classList.contains('ant-col-order-2')).toBe(true); - expect(cols[ 3 ].nativeElement.classList.contains('ant-col-order-1')).toBe(true); + expect(cols[0].nativeElement.classList.contains('ant-col-order-4')).toBe(true); + expect(cols[1].nativeElement.classList.contains('ant-col-order-3')).toBe(true); + expect(cols[2].nativeElement.classList.contains('ant-col-order-2')).toBe(true); + expect(cols[3].nativeElement.classList.contains('ant-col-order-1')).toBe(true); })); }); @@ -151,9 +151,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridGutterComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridGutterComponent], + providers: [] }).compileComponents(); })); @@ -165,21 +165,27 @@ describe('grid', () => { it('should number work', () => { fixture.detectChanges(); - expect(rows[ 0 ].nativeElement.style.cssText).toBe('margin-left: -8px; margin-right: -8px;'); - expect(cols.slice(0, 4).every(col => col.nativeElement.style.cssText === 'padding-left: 8px; padding-right: 8px;')).toBe(true); + expect(rows[0].nativeElement.style.cssText).toBe('margin-left: -8px; margin-right: -8px;'); + expect( + cols.slice(0, 4).every(col => col.nativeElement.style.cssText === 'padding-left: 8px; padding-right: 8px;') + ).toBe(true); expect(cols.slice(0, 4).every(col => col.nativeElement.classList.contains('gutter-row'))).toBe(true); }); it('should responsive work', () => { // TODO: fake media query fixture.detectChanges(); - expect(rows[ 1 ].nativeElement.style.cssText).toBe('margin-left: -4px; margin-right: -4px;'); - expect(cols.slice(4, 8).every(col => col.nativeElement.style.cssText === 'padding-left: 4px; padding-right: 4px;')).toBe(true); + expect(rows[1].nativeElement.style.cssText).toBe('margin-left: -4px; margin-right: -4px;'); + expect( + cols.slice(4, 8).every(col => col.nativeElement.style.cssText === 'padding-left: 4px; padding-right: 4px;') + ).toBe(true); expect(cols.slice(4, 8).every(col => col.nativeElement.classList.contains('gutter-row'))).toBe(true); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); - expect(rows[ 1 ].nativeElement.style.cssText).toBe('margin-left: -4px; margin-right: -4px;'); - expect(cols.slice(4, 8).every(col => col.nativeElement.style.cssText === 'padding-left: 4px; padding-right: 4px;')).toBe(true); + expect(rows[1].nativeElement.style.cssText).toBe('margin-left: -4px; margin-right: -4px;'); + expect( + cols.slice(4, 8).every(col => col.nativeElement.style.cssText === 'padding-left: 4px; padding-right: 4px;') + ).toBe(true); expect(cols.slice(4, 8).every(col => col.nativeElement.classList.contains('gutter-row'))).toBe(true); }); }); @@ -190,9 +196,9 @@ describe('grid', () => { let cols: DebugElement[]; beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridOffsetComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridOffsetComponent], + providers: [] }).compileComponents(); })); @@ -204,11 +210,11 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); expect(rows.every(row => row.nativeElement.classList.contains('ant-row'))).toBe(true); - expect(cols[ 0 ].nativeElement.className).toBe('ant-col-8'); - expect(cols[ 1 ].nativeElement.className).toBe('ant-col-8 ant-col-offset-8'); - expect(cols[ 2 ].nativeElement.className).toBe('ant-col-6 ant-col-offset-6'); - expect(cols[ 3 ].nativeElement.className).toBe('ant-col-6 ant-col-offset-6'); - expect(cols[ 4 ].nativeElement.className).toBe('ant-col-12 ant-col-offset-6'); + expect(cols[0].nativeElement.className).toBe('ant-col-8'); + expect(cols[1].nativeElement.className).toBe('ant-col-8 ant-col-offset-8'); + expect(cols[2].nativeElement.className).toBe('ant-col-6 ant-col-offset-6'); + expect(cols[3].nativeElement.className).toBe('ant-col-6 ant-col-offset-6'); + expect(cols[4].nativeElement.className).toBe('ant-col-12 ant-col-offset-6'); }); }); @@ -218,9 +224,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridResponsiveComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridResponsiveComponent], + providers: [] }).compileComponents(); })); @@ -231,9 +237,11 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(cols[ 0 ].nativeElement.className).toBe('ant-col-xs-2 ant-col-sm-4 ant-col-md-6 ant-col-lg-8 ant-col-xl-10'); - expect(cols[ 1 ].nativeElement.className).toBe('ant-col-xs-20 ant-col-sm-16 ant-col-md-12 ant-col-lg-8 ant-col-xl-4'); - expect(cols[ 2 ].nativeElement.className).toBe('ant-col-xs-2 ant-col-sm-4 ant-col-md-6 ant-col-lg-8 ant-col-xl-10'); + expect(cols[0].nativeElement.className).toBe('ant-col-xs-2 ant-col-sm-4 ant-col-md-6 ant-col-lg-8 ant-col-xl-10'); + expect(cols[1].nativeElement.className).toBe( + 'ant-col-xs-20 ant-col-sm-16 ant-col-md-12 ant-col-lg-8 ant-col-xl-4' + ); + expect(cols[2].nativeElement.className).toBe('ant-col-xs-2 ant-col-sm-4 ant-col-md-6 ant-col-lg-8 ant-col-xl-10'); }); }); @@ -243,9 +251,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridResponsiveMoreComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridResponsiveMoreComponent], + providers: [] }).compileComponents(); })); @@ -255,9 +263,11 @@ describe('grid', () => { }); it('should have correct style', () => { fixture.detectChanges(); - expect(cols[ 0 ].nativeElement.className).toBe('ant-col-xs-5 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2'); - expect(cols[ 1 ].nativeElement.className).toBe('ant-col-xs-11 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2'); - expect(cols[ 2 ].nativeElement.className).toBe('ant-col-xs-5 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2'); + expect(cols[0].nativeElement.className).toBe('ant-col-xs-5 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2'); + expect(cols[1].nativeElement.className).toBe( + 'ant-col-xs-11 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2' + ); + expect(cols[2].nativeElement.className).toBe('ant-col-xs-5 ant-col-xs-offset-1 ant-col-lg-6 ant-col-lg-offset-2'); }); }); @@ -267,9 +277,9 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridSortComponent ], - providers : [] + imports: [NzGridModule], + declarations: [NzDemoGridSortComponent], + providers: [] }).compileComponents(); })); @@ -280,8 +290,8 @@ describe('grid', () => { it('should have correct style', () => { fixture.detectChanges(); - expect(cols[ 0 ].nativeElement.className).toBe('ant-col-18 ant-col-push-6'); - expect(cols[ 1 ].nativeElement.className).toBe('ant-col-6 ant-col-pull-18'); + expect(cols[0].nativeElement.className).toBe('ant-col-18 ant-col-push-6'); + expect(cols[1].nativeElement.className).toBe('ant-col-6 ant-col-pull-18'); }); }); @@ -291,10 +301,10 @@ describe('grid', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzGridModule ], - declarations: [ NzDemoGridPlaygroundComponent ], - providers : [], - schemas : [ NO_ERRORS_SCHEMA ] + imports: [NzGridModule], + declarations: [NzDemoGridPlaygroundComponent], + providers: [], + schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); @@ -308,14 +318,18 @@ describe('grid', () => { const row = fixture.debugElement.query(By.directive(NzRowDirective)); let cols = fixture.debugElement.queryAll(By.directive(NzColDirective)); expect(cols.length).toBe(4); - expect(cols.every(col => col.nativeElement.style.cssText === 'padding-left: 8px; padding-right: 8px;')).toBe(true); + expect(cols.every(col => col.nativeElement.style.cssText === 'padding-left: 8px; padding-right: 8px;')).toBe( + true + ); expect(row.nativeElement.style.cssText).toBe('margin-left: -8px; margin-right: -8px;'); testComponent.gutter = 24; testComponent.count = 12; fixture.detectChanges(); cols = fixture.debugElement.queryAll(By.directive(NzColDirective)); expect(cols.length).toBe(12); - expect(cols.every(col => col.nativeElement.style.cssText === 'padding-left: 12px; padding-right: 12px;')).toBe(true); + expect(cols.every(col => col.nativeElement.style.cssText === 'padding-left: 12px; padding-right: 12px;')).toBe( + true + ); expect(row.nativeElement.style.cssText).toBe('margin-left: -12px; margin-right: -12px;'); }); }); diff --git a/components/grid/nz-row.directive.ts b/components/grid/nz-row.directive.ts index f96e39fb5e4..da8f3a1392e 100644 --- a/components/grid/nz-row.directive.ts +++ b/components/grid/nz-row.directive.ts @@ -34,17 +34,17 @@ export enum Breakpoint { export type BreakpointMap = { [index in keyof typeof Breakpoint]: string }; const responsiveMap: BreakpointMap = { - xs : '(max-width: 575px)', - sm : '(min-width: 576px)', - md : '(min-width: 768px)', - lg : '(min-width: 992px)', - xl : '(min-width: 1200px)', + xs: '(max-width: 575px)', + sm: '(min-width: 576px)', + md: '(min-width: 768px)', + lg: '(min-width: 992px)', + xl: '(min-width: 1200px)', xxl: '(min-width: 1600px)' }; @Directive({ - selector : '[nz-row],nz-row', - providers: [ NzUpdateHostClassService ] + selector: '[nz-row],nz-row', + providers: [NzUpdateHostClassService] }) export class NzRowDirective implements OnInit, OnChanges, AfterViewInit, OnDestroy { @Input() nzType: NzType; @@ -61,8 +61,8 @@ export class NzRowDirective implements OnInit, OnChanges, AfterViewInit, OnDestr calculateGutter(): number { if (typeof this.nzGutter !== 'object') { return this.nzGutter; - } else if (this.breakPoint && this.nzGutter[ this.breakPoint ]) { - return this.nzGutter[ this.breakPoint ]; + } else if (this.breakPoint && this.nzGutter[this.breakPoint]) { + return this.nzGutter[this.breakPoint]; } else { return 0; } @@ -81,7 +81,7 @@ export class NzRowDirective implements OnInit, OnChanges, AfterViewInit, OnDestr watchMedia(): void { // @ts-ignore Object.keys(responsiveMap).map((screen: Breakpoint) => { - const matchBelow = this.mediaMatcher.matchMedia(responsiveMap[ screen ]).matches; + const matchBelow = this.mediaMatcher.matchMedia(responsiveMap[screen]).matches; if (matchBelow) { this.breakPoint = screen; } @@ -92,16 +92,22 @@ export class NzRowDirective implements OnInit, OnChanges, AfterViewInit, OnDestr /** temp solution since no method add classMap to host https://github.com/angular/angular/issues/7289*/ setClassMap(): void { const classMap = { - [ `${this.prefixCls}` ] : !this.nzType, - [ `${this.prefixCls}-${this.nzType}` ] : this.nzType, - [ `${this.prefixCls}-${this.nzType}-${this.nzAlign}` ] : this.nzType && this.nzAlign, - [ `${this.prefixCls}-${this.nzType}-${this.nzJustify}` ]: this.nzType && this.nzJustify + [`${this.prefixCls}`]: !this.nzType, + [`${this.prefixCls}-${this.nzType}`]: this.nzType, + [`${this.prefixCls}-${this.nzType}-${this.nzAlign}`]: this.nzType && this.nzAlign, + [`${this.prefixCls}-${this.nzType}-${this.nzJustify}`]: this.nzType && this.nzJustify }; this.nzUpdateHostClassService.updateHostClass(this.el, classMap); } - constructor(public elementRef: ElementRef, public renderer: Renderer2, public nzUpdateHostClassService: NzUpdateHostClassService, public mediaMatcher: MediaMatcher, public ngZone: NgZone, public platform: Platform) { - } + constructor( + public elementRef: ElementRef, + public renderer: Renderer2, + public nzUpdateHostClassService: NzUpdateHostClassService, + public mediaMatcher: MediaMatcher, + public ngZone: NgZone, + public platform: Platform + ) {} ngOnInit(): void { this.setClassMap(); @@ -121,8 +127,11 @@ export class NzRowDirective implements OnInit, OnChanges, AfterViewInit, OnDestr if (this.platform.isBrowser) { this.ngZone.runOutsideAngular(() => { fromEvent(window, 'resize') - .pipe(auditTime(16), takeUntil(this.destroy$)) - .subscribe(() => this.watchMedia()); + .pipe( + auditTime(16), + takeUntil(this.destroy$) + ) + .subscribe(() => this.watchMedia()); }); } } diff --git a/components/i18n/date-helper.service.spec.ts b/components/i18n/date-helper.service.spec.ts index 4ba3a9f17ce..ceac7e8529f 100644 --- a/components/i18n/date-helper.service.spec.ts +++ b/components/i18n/date-helper.service.spec.ts @@ -15,10 +15,8 @@ describe('DateHelperService', () => { describe('Formatting with DatePipe', () => { beforeEach(() => { injector = TestBed.configureTestingModule({ - imports: [ NzI18nModule ], - providers: [ - { provide: NZ_I18N, useValue: en_US } - ] + imports: [NzI18nModule], + providers: [{ provide: NZ_I18N, useValue: en_US }] }); dateHelper = injector.get(DateHelperService); @@ -42,10 +40,8 @@ describe('DateHelperService', () => { describe('Formatting with Data-fns', () => { beforeEach(() => { injector = TestBed.configureTestingModule({ - imports: [ NzI18nModule ], - providers: [ - { provide: NZ_DATE_LOCALE, useValue: enDateLocale } - ] + imports: [NzI18nModule], + providers: [{ provide: NZ_DATE_LOCALE, useValue: enDateLocale }] }); dateHelper = injector.get(DateHelperService); @@ -65,10 +61,8 @@ describe('DateHelperService', () => { describe('Custom firstDayOfWeek', () => { beforeEach(() => { injector = TestBed.configureTestingModule({ - imports: [ NzI18nModule ], - providers: [ - { provide: NZ_DATE_CONFIG, useValue: { firstDayOfWeek: 4 } } - ] + imports: [NzI18nModule], + providers: [{ provide: NZ_DATE_CONFIG, useValue: { firstDayOfWeek: 4 } }] }); dateHelper = injector.get(DateHelperService); @@ -78,5 +72,4 @@ describe('DateHelperService', () => { expect(dateHelper.getFirstDayOfWeek()).toBe(4); }); }); - }); diff --git a/components/i18n/date-helper.service.ts b/components/i18n/date-helper.service.ts index 34921141b91..fd7a87a142a 100644 --- a/components/i18n/date-helper.service.ts +++ b/components/i18n/date-helper.service.ts @@ -6,9 +6,15 @@ import fnsParse from 'date-fns/parse'; import { mergeDateConfig, NzDateConfig, NZ_DATE_CONFIG } from './date-config'; import { NzI18nService } from './nz-i18n.service'; -export function DATE_HELPER_SERVICE_FACTORY(injector: Injector, config: NzDateConfig, datePipe: DatePipe): DateHelperService { +export function DATE_HELPER_SERVICE_FACTORY( + injector: Injector, + config: NzDateConfig, + datePipe: DatePipe +): DateHelperService { const i18n = injector.get(NzI18nService); - return i18n.getDateLocale() ? new DateHelperByDateFns(i18n, config) : new DateHelperByDatePipe(i18n, config, datePipe); + return i18n.getDateLocale() + ? new DateHelperByDateFns(i18n, config) + : new DateHelperByDatePipe(i18n, config, datePipe); } /** @@ -18,7 +24,7 @@ export function DATE_HELPER_SERVICE_FACTORY(injector: Injector, config: NzDateCo @Injectable({ providedIn: 'root', useFactory: DATE_HELPER_SERVICE_FACTORY, - deps: [ Injector, [ new Optional(), NZ_DATE_CONFIG ], DatePipe ] + deps: [Injector, [new Optional(), NZ_DATE_CONFIG], DatePipe] }) export abstract class DateHelperService { relyOnDatePipe: boolean = this instanceof DateHelperByDatePipe; // Indicate whether this service is rely on DatePipe @@ -78,7 +84,11 @@ export class DateHelperByDateFns extends DateHelperService { * @deprecated Maybe removed in next major version due to this serious bug */ export class DateHelperByDatePipe extends DateHelperService { - constructor(i18n: NzI18nService, @Optional() @Inject(NZ_DATE_CONFIG) config: NzDateConfig, private datePipe: DatePipe) { + constructor( + i18n: NzI18nService, + @Optional() @Inject(NZ_DATE_CONFIG) config: NzDateConfig, + private datePipe: DatePipe + ) { super(i18n, config); } @@ -89,15 +99,13 @@ export class DateHelperByDatePipe extends DateHelperService { getFirstDayOfWeek(): WeekDayIndex { if (this.config.firstDayOfWeek === undefined) { const locale = this.i18n.getLocaleId(); - return locale && [ 'zh-cn', 'zh-tw' ].indexOf(locale.toLowerCase()) > -1 ? 1 : 0; + return locale && ['zh-cn', 'zh-tw'].indexOf(locale.toLowerCase()) > -1 ? 1 : 0; } return this.config.firstDayOfWeek; } format(date: Date, formatStr: string): string { - return date - ? this.datePipe.transform(date, formatStr, undefined, this.i18n.getLocaleId())! - : ''; + return date ? this.datePipe.transform(date, formatStr, undefined, this.i18n.getLocaleId())! : ''; } /** @@ -111,9 +119,12 @@ export class DateHelperByDatePipe extends DateHelperService { * @param format input format pattern */ transCompatFormat(format: string): string { - return format && format - .replace(/Y/g, 'y') // only support y, yy, yyy, yyyy - .replace(/D/g, 'd'); // d, dd represent of D, DD for momentjs, others are not support + return ( + format && + format + .replace(/Y/g, 'y') // only support y, yy, yyy, yyyy + .replace(/D/g, 'd') + ); // d, dd represent of D, DD for momentjs, others are not support } } diff --git a/components/i18n/nz-i18n.module.ts b/components/i18n/nz-i18n.module.ts index f751903ec7b..3484256fa46 100644 --- a/components/i18n/nz-i18n.module.ts +++ b/components/i18n/nz-i18n.module.ts @@ -7,14 +7,9 @@ import { NzI18nPipe } from './nz-i18n.pipe'; import { NZ_DATE_LOCALE, NZ_I18N } from './nz-i18n.token'; @NgModule({ - imports : [ LoggerModule ], - declarations: [ NzI18nPipe ], - exports : [ NzI18nPipe ], - providers : [ - DatePipe, - { provide: NZ_I18N, useValue: null }, - { provide: NZ_DATE_LOCALE, useValue: null } - ] + imports: [LoggerModule], + declarations: [NzI18nPipe], + exports: [NzI18nPipe], + providers: [DatePipe, { provide: NZ_I18N, useValue: null }, { provide: NZ_DATE_LOCALE, useValue: null }] }) -export class NzI18nModule { -} +export class NzI18nModule {} diff --git a/components/i18n/nz-i18n.pipe.ts b/components/i18n/nz-i18n.pipe.ts index 5bc5cdf9781..8a47e1abcde 100644 --- a/components/i18n/nz-i18n.pipe.ts +++ b/components/i18n/nz-i18n.pipe.ts @@ -6,8 +6,7 @@ import { NzI18nService } from './nz-i18n.service'; name: 'nzI18n' }) export class NzI18nPipe implements PipeTransform { - constructor(private _locale: NzI18nService) { - } + constructor(private _locale: NzI18nService) {} transform(path: string, keyValue?: object): string { return this._locale.translate(path, keyValue); diff --git a/components/i18n/nz-i18n.service.spec.ts b/components/i18n/nz-i18n.service.spec.ts index f9647dda304..a56eb071f8f 100644 --- a/components/i18n/nz-i18n.service.spec.ts +++ b/components/i18n/nz-i18n.service.spec.ts @@ -36,5 +36,4 @@ describe('nz-i18n.service', () => { expect(srv['_change'].next).not.toHaveBeenCalled(); }); }); - }); diff --git a/components/i18n/nz-i18n.service.ts b/components/i18n/nz-i18n.service.ts index f6d7ed41933..2f2c795b669 100644 --- a/components/i18n/nz-i18n.service.ts +++ b/components/i18n/nz-i18n.service.ts @@ -18,10 +18,7 @@ export class NzI18nService { return this._change.asObservable(); } - constructor( - @Inject(NZ_I18N) locale: NzI18nInterface, - @Inject(NZ_DATE_LOCALE) dateLocale: DateLocale) { - + constructor(@Inject(NZ_I18N) locale: NzI18nInterface, @Inject(NZ_DATE_LOCALE) dateLocale: DateLocale) { this.setLocale(locale || zh_CN); this.setDateLocale(dateLocale || null); } @@ -34,7 +31,7 @@ export class NzI18nService { let content = this._getObjectPath(this._locale, path) as string; if (typeof content === 'string') { if (data) { - Object.keys(data).forEach((key) => content = content.replace(new RegExp(`%${key}%`, 'g'), data[ key ])); + Object.keys(data).forEach(key => (content = content.replace(new RegExp(`%${key}%`, 'g'), data[key]))); } return content; } @@ -75,18 +72,20 @@ export class NzI18nService { * @param path dot paths for finding exist value from locale data, eg. "a.b.c" * @param defaultValue default value if the result is not "truthy" */ - getLocaleData(path?: string, defaultValue?: any): any { // tslint:disable-line:no-any + // tslint:disable-next-line:no-any + getLocaleData(path?: string, defaultValue?: any): any { const result = path ? this._getObjectPath(this._locale, path) : this._locale; return result || defaultValue; } - private _getObjectPath(obj: IndexableObject, path: string): string | object | any { // tslint:disable-line:no-any + // tslint:disable-next-line:no-any + private _getObjectPath(obj: IndexableObject, path: string): string | object | any { let res = obj; const paths = path.split('.'); const depth = paths.length; let index = 0; while (res && index < depth) { - res = res[ paths[ index++ ] ]; + res = res[paths[index++]]; } return index === depth ? res : null; } diff --git a/components/icon/demo/basic.ts b/components/icon/demo/basic.ts index c95b47330e4..777e5c1b87f 100644 --- a/components/icon/demo/basic.ts +++ b/components/icon/demo/basic.ts @@ -13,12 +13,13 @@ import { Component } from '@angular/core'; `, - styles: [ ` - [nz-icon] { - margin-right: 6px; - font-size: 24px; - } - `] + styles: [ + ` + [nz-icon] { + margin-right: 6px; + font-size: 24px; + } + ` + ] }) -export class NzDemoIconBasicComponent { -} +export class NzDemoIconBasicComponent {} diff --git a/components/icon/demo/custom.ts b/components/icon/demo/custom.ts index 38796cf242c..9e26c4c2eab 100644 --- a/components/icon/demo/custom.ts +++ b/components/icon/demo/custom.ts @@ -6,29 +6,64 @@ import { Component } from '@angular/core';
- + - - - - - - - - + + + + + + + +
`, - styles : [ ` - [nz-icon] { - margin-right: 6px; - font-size: 24px; - } - ` ] + styles: [ + ` + [nz-icon] { + margin-right: 6px; + font-size: 24px; + } + ` + ] }) -export class NzDemoIconCustomComponent { -} +export class NzDemoIconCustomComponent {} diff --git a/components/icon/demo/iconfont.ts b/components/icon/demo/iconfont.ts index 2b50d509059..6c67f1e8400 100644 --- a/components/icon/demo/iconfont.ts +++ b/components/icon/demo/iconfont.ts @@ -6,16 +6,18 @@ import { NzIconService } from 'ng-zorro-antd'; template: `
- +
`, - styles : [ ` - [nz-icon] { - margin-right: 6px; - font-size: 24px; - } - ` ] + styles: [ + ` + [nz-icon] { + margin-right: 6px; + font-size: 24px; + } + ` + ] }) export class NzDemoIconIconfontComponent { constructor(private _iconService: NzIconService) { diff --git a/components/icon/demo/namespace.ts b/components/icon/demo/namespace.ts index 2231f537f0b..ba209ee72c3 100644 --- a/components/icon/demo/namespace.ts +++ b/components/icon/demo/namespace.ts @@ -1,7 +1,8 @@ import { Component } from '@angular/core'; import { NzIconService } from 'ng-zorro-antd'; -const ngZorroIconLiteral = '\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n'; +const ngZorroIconLiteral = + '\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n'; @Component({ selector: 'nz-demo-icon-namespace', @@ -10,12 +11,14 @@ const ngZorroIconLiteral = ' `, - styles: [ ` - [nz-icon] { - margin-right: 6px; - font-size: 24px; - } - ` ] + styles: [ + ` + [nz-icon] { + margin-right: 6px; + font-size: 24px; + } + ` + ] }) export class NzDemoIconNamespaceComponent { constructor(private _iconService: NzIconService) { diff --git a/components/icon/demo/twotone.ts b/components/icon/demo/twotone.ts index e5d80aa65f7..ae64a8167d7 100644 --- a/components/icon/demo/twotone.ts +++ b/components/icon/demo/twotone.ts @@ -9,12 +9,13 @@ import { Component } from '@angular/core'; `, - styles : [ ` - .icons-list > .anticon { - margin-right: 6px; - font-size: 24px; - } - ` ] + styles: [ + ` + .icons-list > .anticon { + margin-right: 6px; + font-size: 24px; + } + ` + ] }) -export class NzDemoIconTwotoneComponent { -} +export class NzDemoIconTwotoneComponent {} diff --git a/components/icon/nz-icon-test.module.ts b/components/icon/nz-icon-test.module.ts index 3e4a4e708e0..ba00fd146ea 100644 --- a/components/icon/nz-icon-test.module.ts +++ b/components/icon/nz-icon-test.module.ts @@ -16,9 +16,7 @@ const icons: IconDefinition[] = Object.keys(antDesignIcons).map(key => antDesign */ // @dynamic @NgModule({ - exports: [ - NzIconModule - ], + exports: [NzIconModule], providers: [ { provide: NZ_ICONS, diff --git a/components/icon/nz-icon.directive.ts b/components/icon/nz-icon.directive.ts index ea280e20571..a9400a07fc2 100644 --- a/components/icon/nz-icon.directive.ts +++ b/components/icon/nz-icon.directive.ts @@ -15,17 +15,17 @@ import { NzIconService } from './nz-icon.service'; const iconTypeRE = /^anticon\-\w/; -const getIconTypeClass = (className: string): { name: string, index: number } | undefined => { +const getIconTypeClass = (className: string): { name: string; index: number } | undefined => { if (!className) { return undefined; } else { const classArr = className.split(/\s/); - const index = classArr.findIndex((cls => cls !== 'anticon' && cls !== 'anticon-spin' && !!cls.match(iconTypeRE))); - return index === -1 ? undefined : { name: classArr[ index ], index }; + const index = classArr.findIndex(cls => cls !== 'anticon' && cls !== 'anticon-spin' && !!cls.match(iconTypeRE)); + return index === -1 ? undefined : { name: classArr[index], index }; } }; -const normalizeType = (rawType: string): { type: string, crossError: boolean, verticalError: boolean } => { +const normalizeType = (rawType: string): { type: string; crossError: boolean; verticalError: boolean } => { const ret = { type: rawType, crossError: false, verticalError: false }; ret.type = rawType ? rawType.replace('anticon-', '') : ''; if (ret.type.includes('verticle')) { @@ -56,12 +56,22 @@ const normalizeType = (rawType: string): { type: string, crossError: boolean, ve }) export class NzIconDirective extends IconDirective implements OnInit, OnChanges, OnDestroy, AfterContentChecked { /** Properties with `nz` prefix. */ - @Input() @InputBoolean() set nzSpin(value: boolean) { this.spin = value; } + @Input() @InputBoolean() set nzSpin(value: boolean) { + this.spin = value; + } @Input() nzRotate: number = 0; - @Input() set nzType(value: string) { this.type = value; } - @Input() set nzTheme(value: ThemeType) { this.theme = value; } - @Input() set nzTwotoneColor(value: string) { this.twoToneColor = value; } - @Input() set nzIconfont(value: string) { this.iconfont = value; } + @Input() set nzType(value: string) { + this.type = value; + } + @Input() set nzTheme(value: ThemeType) { + this.theme = value; + } + @Input() set nzTwotoneColor(value: string) { + this.twoToneColor = value; + } + @Input() set nzIconfont(value: string) { + this.iconfont = value; + } /** @deprecated 8.0.0 avoid exposing low layer API. */ @Input() spin = false; @@ -98,14 +108,13 @@ export class NzIconDirective extends IconDirective implements OnInit, OnChanges, if (!oldAPI) { this.setClassName(); } - this._changeIcon() - .then(svg => { - this.setSVGData(svg); - if (!oldAPI && svg) { - this.handleSpin(svg); - this.handleRotate(svg); - } - }); + this._changeIcon().then(svg => { + this.setSVGData(svg); + if (!oldAPI && svg) { + this.handleSpin(svg); + this.handleRotate(svg); + } + }); } private classChangeHandler(className: string): void { @@ -211,7 +220,7 @@ export class NzIconDirective extends IconDirective implements OnInit, OnChanges, let length = children.length; if (!this.type && children.length) { while (length--) { - const child = children[ length ]; + const child = children[length]; if (child.tagName.toLowerCase() === 'svg') { this.iconService.normalizeSvgElement(child as SVGElement); } diff --git a/components/icon/nz-icon.module.ts b/components/icon/nz-icon.module.ts index 971cc26dae2..0b1a1daa4ec 100644 --- a/components/icon/nz-icon.module.ts +++ b/components/icon/nz-icon.module.ts @@ -2,8 +2,7 @@ import { NgModule } from '@angular/core'; import { NzIconDirective } from './nz-icon.directive'; @NgModule({ - exports : [ NzIconDirective ], - declarations: [ NzIconDirective ] + exports: [NzIconDirective], + declarations: [NzIconDirective] }) -export class NzIconModule { -} +export class NzIconModule {} diff --git a/components/icon/nz-icon.spec.ts b/components/icon/nz-icon.spec.ts index a053e594cb6..123ff482937 100644 --- a/components/icon/nz-icon.spec.ts +++ b/components/icon/nz-icon.spec.ts @@ -18,7 +18,7 @@ import { NzIconService, NZ_ICON_DEFAULT_TWOTONE_COLOR, NZ_ICONS } from './nz-ico describe('nz icon', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzIconModule ], + imports: [CommonModule, NzIconModule], declarations: [ NzTestIconExtensionsComponent, NzTestIconCustomComponent, @@ -26,9 +26,9 @@ describe('nz icon', () => { NzTestIconOldApiComponent, NzTestIconPrefixComponent ], - providers : [ + providers: [ { - provide : NZ_ICONS, + provide: NZ_ICONS, useValue: [ LeftOutline, RightOutline, @@ -39,7 +39,7 @@ describe('nz icon', () => { ] }, { - provide : NZ_ICON_DEFAULT_TWOTONE_COLOR, + provide: NZ_ICON_DEFAULT_TWOTONE_COLOR, useValue: '#3344cc' } ] @@ -62,71 +62,71 @@ describe('nz icon', () => { it('should get icon class name back', () => { fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.classList.contains('anticon')).toBe(true); - expect(icons[ 0 ].nativeElement.classList.contains('anticon-question')).toBe(true); - expect(icons[ 1 ].nativeElement.classList.contains('anticon-loading')).toBe(true); + expect(icons[0].nativeElement.classList.contains('anticon')).toBe(true); + expect(icons[0].nativeElement.classList.contains('anticon-question')).toBe(true); + expect(icons[1].nativeElement.classList.contains('anticon-loading')).toBe(true); }); it('should change class name when type changes', () => { testComponent.type = 'question-circle'; fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.classList.contains('anticon')).toBe(true); - expect(icons[ 0 ].nativeElement.classList.contains('anticon-question-circle')).toBe(true); - expect(icons[ 0 ].nativeElement.classList.contains('anticon-question')).not.toBe(true); + expect(icons[0].nativeElement.classList.contains('anticon')).toBe(true); + expect(icons[0].nativeElement.classList.contains('anticon-question-circle')).toBe(true); + expect(icons[0].nativeElement.classList.contains('anticon-question')).not.toBe(true); }); it('should support spin and cancel', fakeAsync(() => { fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(true); + expect(icons[0].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(true); testComponent.spin = false; fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(false); + expect(icons[0].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(false); })); it('should make loading spin', fakeAsync(() => { fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 1 ].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(true); + expect(icons[1].nativeElement.firstChild.classList.contains('anticon-spin')).toBe(true); })); it('should type support old API', () => { testComponent.type = 'anticon anticon-cross'; fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.className).toContain('anticon'); - expect(icons[ 0 ].nativeElement.className).toContain('anticon-close'); - expect(icons[ 0 ].nativeElement.innerHTML).toContain('svg'); + expect(icons[0].nativeElement.className).toContain('anticon'); + expect(icons[0].nativeElement.className).toContain('anticon-close'); + expect(icons[0].nativeElement.innerHTML).toContain('svg'); // An invalid type should not affect the actual type. testComponent.type = 'anticon'; fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.className).toContain('anticon'); - expect(icons[ 0 ].nativeElement.className).toContain('anticon-close'); - expect(icons[ 0 ].nativeElement.innerHTML).toContain('svg'); + expect(icons[0].nativeElement.className).toContain('anticon'); + expect(icons[0].nativeElement.className).toContain('anticon-close'); + expect(icons[0].nativeElement.innerHTML).toContain('svg'); }); it('should rotate work', fakeAsync(() => { fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.firstChild.style.transform).toBeFalsy(); + expect(icons[0].nativeElement.firstChild.style.transform).toBeFalsy(); testComponent.rotate = 120; fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.firstChild.style.transform).toBe('rotate(120deg)'); + expect(icons[0].nativeElement.firstChild.style.transform).toBe('rotate(120deg)'); testComponent.rotate = 0; fixture.detectChanges(); tick(1000); fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.firstChild.style.transform).toBeFalsy(); + expect(icons[0].nativeElement.firstChild.style.transform).toBeFalsy(); })); }); @@ -141,10 +141,12 @@ describe('nz icon', () => { it('should support custom svg element', () => { fixture.detectChanges(); icons = fixture.debugElement.queryAll(By.directive(NzIconDirective)); - const icon1 = icons[ 0 ]; + const icon1 = icons[0]; expect(icon1.nativeElement.className).toContain('anticon'); expect(icon1.nativeElement.innerHTML).toContain('svg'); - expect(icon1.nativeElement.innerHTML).toContain('viewBox="0 0 1024 1024" width="1em" height="1em" fill="currentColor"'); + expect(icon1.nativeElement.innerHTML).toContain( + 'viewBox="0 0 1024 1024" width="1em" height="1em" fill="currentColor"' + ); }); }); @@ -161,10 +163,10 @@ describe('nz icon', () => { fixture.whenStable().then(() => { fixture.detectChanges(); icons = fixture.debugElement.queryAll(By.directive(NzIconDirective)); - expect(icons[ 0 ].nativeElement.className).toContain('anticon'); - expect(icons[ 0 ].nativeElement.innerHTML).toContain('xlink:href="#icon-tuichu"'); - expect(icons[ 1 ].nativeElement.innerHTML).toContain('link:href="#icon-facebook"'); - expect(icons[ 2 ].nativeElement.innerHTML).toContain('xlink:href="#icon-twitter"'); + expect(icons[0].nativeElement.className).toContain('anticon'); + expect(icons[0].nativeElement.innerHTML).toContain('xlink:href="#icon-tuichu"'); + expect(icons[1].nativeElement.innerHTML).toContain('link:href="#icon-facebook"'); + expect(icons[2].nativeElement.innerHTML).toContain('xlink:href="#icon-twitter"'); }); })); }); @@ -180,8 +182,8 @@ describe('nz icon', () => { it('should be compatible to old API', () => { fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.className).toContain('anticon'); - expect(icons[ 0 ].nativeElement.innerHTML).toContain('svg'); + expect(icons[0].nativeElement.className).toContain('anticon'); + expect(icons[0].nativeElement.innerHTML).toContain('svg'); }); }); @@ -196,9 +198,9 @@ describe('nz icon', () => { it('should prefixes work', () => { fixture.detectChanges(); - expect(icons[ 0 ].nativeElement.className).toContain('anticon'); - expect(icons[ 0 ].nativeElement.className).toContain('anticon-question'); - expect(icons[ 0 ].nativeElement.innerHTML).toContain('svg'); + expect(icons[0].nativeElement.className).toContain('anticon'); + expect(icons[0].nativeElement.className).toContain('anticon-question'); + expect(icons[0].nativeElement.innerHTML).toContain('svg'); }); }); }); @@ -209,15 +211,15 @@ describe('nz icon twotone color injection', () => { it('should support default twotone color', () => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzIconModule ], - declarations: [ NzTestIconExtensionsComponent ], - providers : [ + imports: [CommonModule, NzIconModule], + declarations: [NzTestIconExtensionsComponent], + providers: [ { - provide : NZ_ICONS, - useValue: [ LeftOutline, RightOutline, QuestionOutline ] + provide: NZ_ICONS, + useValue: [LeftOutline, RightOutline, QuestionOutline] }, { - provide : NZ_ICON_DEFAULT_TWOTONE_COLOR, + provide: NZ_ICON_DEFAULT_TWOTONE_COLOR, useValue: '#3344cc' } ] @@ -227,21 +229,21 @@ describe('nz icon twotone color injection', () => { fixture.detectChanges(); icons = fixture.debugElement.queryAll(By.directive(NzIconDirective)); - expect(icons[ 0 ].nativeElement.querySelector('svg')).not.toBe(null); - expect(icons[ 0 ].componentInstance._iconService.twoToneColor.primaryColor).toBe('#3344cc'); + expect(icons[0].nativeElement.querySelector('svg')).not.toBe(null); + expect(icons[0].componentInstance._iconService.twoToneColor.primaryColor).toBe('#3344cc'); }); it('should not set non-hashed-started string', () => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzIconModule ], - declarations: [ NzTestIconExtensionsComponent ], - providers : [ + imports: [CommonModule, NzIconModule], + declarations: [NzTestIconExtensionsComponent], + providers: [ { - provide : NZ_ICONS, - useValue: [ LeftOutline, RightOutline, QuestionOutline ] + provide: NZ_ICONS, + useValue: [LeftOutline, RightOutline, QuestionOutline] }, { - provide : NZ_ICON_DEFAULT_TWOTONE_COLOR, + provide: NZ_ICON_DEFAULT_TWOTONE_COLOR, useValue: '3344cc' } ] @@ -251,8 +253,8 @@ describe('nz icon twotone color injection', () => { icons = fixture.debugElement.queryAll(By.directive(NzIconDirective)); fixture.detectChanges(); - expect(icons[ 0 ].componentInstance._iconService.twoToneColor.primaryColor).not.toBe('3344cc'); - expect(icons[ 0 ].componentInstance._iconService.twoToneColor.primaryColor).toBe('#1890ff'); + expect(icons[0].componentInstance._iconService.twoToneColor.primaryColor).not.toBe('3344cc'); + expect(icons[0].componentInstance._iconService.twoToneColor.primaryColor).toBe('#1890ff'); }); }); @@ -269,8 +271,7 @@ export class NzTestIconExtensionsComponent { spin = true; rotate = 0; - constructor(public _iconService: NzIconService) { - } + constructor(public _iconService: NzIconService) {} } @Component({ @@ -279,8 +280,7 @@ export class NzTestIconExtensionsComponent { ` }) -export class NzTestIconPrefixComponent { -} +export class NzTestIconPrefixComponent {} @Component({ selector: 'nz-test-icon-custom', @@ -288,13 +288,13 @@ export class NzTestIconPrefixComponent { + d="M923 283.6c-13.4-31.1-32.6-58.9-56.9-82.8-24.3-23.8-52.5-42.4-84-55.5-32.5-13.5-66.9-20.3-102.4-20.3-49.3 0-97.4 13.5-139.2 39-10 6.1-19.5 12.8-28.5 20.1-9-7.3-18.5-14-28.5-20.1-41.8-25.5-89.9-39-139.2-39-35.5 0-69.9 6.8-102.4 20.3-31.4 13-59.7 31.7-84 55.5-24.4 23.9-43.5 51.7-56.9 82.8-13.9 32.3-21 66.6-21 101.9 0 33.3 6.8 68 20.3 103.3 11.3 29.5 27.5 60.1 48.2 91 32.8 48.9 77.9 99.9 133.9 151.6 92.8 85.7 184.7 144.9 188.6 147.3l23.7 15.2c10.5 6.7 24 6.7 34.5 0l23.7-15.2c3.9-2.5 95.7-61.6 188.6-147.3 56-51.7 101.1-102.7 133.9-151.6 20.7-30.9 37-61.5 48.2-91 13.5-35.3 20.3-70 20.3-103.3 0.1-35.3-7-69.6-20.9-101.9z" + /> ` }) -export class NzTestIconCustomComponent { -} +export class NzTestIconCustomComponent {} @Component({ selector: 'nz-test-icon-iconfont', @@ -320,5 +320,4 @@ export class NzTestIconIconfontComponent { ` }) -export class NzTestIconOldApiComponent { -} +export class NzTestIconOldApiComponent {} diff --git a/components/input-number/demo/digit.ts b/components/input-number/demo/digit.ts index 3517a8cb027..a23cc9665e3 100644 --- a/components/input-number/demo/digit.ts +++ b/components/input-number/demo/digit.ts @@ -2,7 +2,15 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-input-number-digit', - template: `` + template: ` + + ` }) export class NzDemoInputNumberDigitComponent { demoValue: number; diff --git a/components/input-number/demo/disabled.ts b/components/input-number/demo/disabled.ts index 4d6c835a732..fa484da60f1 100644 --- a/components/input-number/demo/disabled.ts +++ b/components/input-number/demo/disabled.ts @@ -3,12 +3,19 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-input-number-disabled', template: ` - +
-
` + + ` }) export class NzDemoInputNumberDisabledComponent { demoValue = 3; diff --git a/components/input-number/demo/formatter.ts b/components/input-number/demo/formatter.ts index e286a1188e7..1f0c34febcc 100644 --- a/components/input-number/demo/formatter.ts +++ b/components/input-number/demo/formatter.ts @@ -3,11 +3,25 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-input-number-formatter', template: ` - - + + `, - styles : [ - ` + styles: [ + ` nz-input-number { margin-right: 8px; } diff --git a/components/input-number/demo/size.ts b/components/input-number/demo/size.ts index bde0e3d8d88..53686715990 100644 --- a/components/input-number/demo/size.ts +++ b/components/input-number/demo/size.ts @@ -5,9 +5,10 @@ import { Component } from '@angular/core'; template: ` - `, - styles : [ - ` + + `, + styles: [ + ` nz-input-number { margin-right: 8px; } diff --git a/components/input-number/nz-input-number.component.ts b/components/input-number/nz-input-number.component.ts index f5f3acd2564..8d2e761c86a 100644 --- a/components/input-number/nz-input-number.component.ts +++ b/components/input-number/nz-input-number.component.ts @@ -25,21 +25,21 @@ import { isNotNil } from '../core/util/check'; import { InputBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-input-number', - templateUrl : './nz-input-number.component.html', - providers : [ + selector: 'nz-input-number', + templateUrl: './nz-input-number.component.html', + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzInputNumberComponent), - multi : true + multi: true } ], changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - host : { - '[class.ant-input-number-focused]' : 'isFocused', - '[class.ant-input-number-lg]' : `nzSize === 'large'`, - '[class.ant-input-number-sm]' : `nzSize === 'small'`, + encapsulation: ViewEncapsulation.None, + host: { + '[class.ant-input-number-focused]': 'isFocused', + '[class.ant-input-number-lg]': `nzSize === 'large'`, + '[class.ant-input-number-sm]': `nzSize === 'small'`, '[class.ant-input-number-disabled]': 'nzDisabled' } }) @@ -65,9 +65,9 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn @Input() nzStep = 1; @Input() @InputBoolean() nzDisabled = false; @Input() @InputBoolean() nzAutoFocus = false; - @Input() nzFormatter: (value: number) => string | number = (value) => value; + @Input() nzFormatter: (value: number) => string | number = value => value; - [ property: string ]: any // tslint:disable-line:no-any + [property: string]: any; // tslint:disable-line:no-any updateAutoFocus(): void { if (this.nzAutoFocus) { @@ -78,7 +78,12 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn } onModelChange(value: string): void { - this.actualValue = this.nzParser(value.trim().replace(/。/g, '.').replace(/[^\w\.-]+/g, '')); + this.actualValue = this.nzParser( + value + .trim() + .replace(/。/g, '.') + .replace(/[^\w\.-]+/g, '') + ); this.inputElement.nativeElement.value = this.actualValue; } @@ -207,9 +212,7 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn const precision = Math.abs(this.getMaxPrecision(val, rat)); let result; if (typeof val === 'number') { - result = - ((precisionFactor * val + precisionFactor * this.nzStep * rat) / - precisionFactor).toFixed(precision); + result = ((precisionFactor * val + precisionFactor * this.nzStep * rat) / precisionFactor).toFixed(precision); } else { result = this.nzMin === -Infinity ? this.nzStep : this.nzMin; } @@ -221,9 +224,7 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn const precision = Math.abs(this.getMaxPrecision(val, rat)); let result; if (typeof val === 'number') { - result = - ((precisionFactor * val - precisionFactor * this.nzStep * rat) / - precisionFactor).toFixed(precision); + result = ((precisionFactor * val - precisionFactor * this.nzStep * rat) / precisionFactor).toFixed(precision); } else { result = this.nzMin === -Infinity ? -this.nzStep : this.nzMin; } @@ -255,7 +256,7 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn return; } this.autoStepTimer = setTimeout(() => { - this[ type ](e, ratio, true); + this[type](e, ratio, true); }, 600); } @@ -266,7 +267,7 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn } setValue(value: number, emit: boolean): void { - if (emit && (`${this.value}` !== `${value}`)) { + if (emit && `${this.value}` !== `${value}`) { this.onChange(value); } this.value = value; @@ -284,7 +285,6 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn this.disabledDown = true; } } - } onKeyDown(e: KeyboardEvent): void { @@ -331,7 +331,12 @@ export class NzInputNumberComponent implements ControlValueAccessor, AfterViewIn this.inputElement.nativeElement.blur(); } - constructor(private elementRef: ElementRef, private renderer: Renderer2, private cdr: ChangeDetectorRef, private focusMonitor: FocusMonitor) { + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + private cdr: ChangeDetectorRef, + private focusMonitor: FocusMonitor + ) { renderer.addClass(elementRef.nativeElement, 'ant-input-number'); } diff --git a/components/input-number/nz-input-number.module.ts b/components/input-number/nz-input-number.module.ts index 97f9791398c..216e5b656b2 100644 --- a/components/input-number/nz-input-number.module.ts +++ b/components/input-number/nz-input-number.module.ts @@ -6,9 +6,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzInputNumberComponent } from './nz-input-number.component'; @NgModule({ - imports : [ CommonModule, FormsModule, NzIconModule ], - declarations: [ NzInputNumberComponent ], - exports : [ NzInputNumberComponent ] + imports: [CommonModule, FormsModule, NzIconModule], + declarations: [NzInputNumberComponent], + exports: [NzInputNumberComponent] }) -export class NzInputNumberModule { -} +export class NzInputNumberModule {} diff --git a/components/input-number/nz-input-number.spec.ts b/components/input-number/nz-input-number.spec.ts index b255c6a79f2..a4eb5668c5f 100644 --- a/components/input-number/nz-input-number.spec.ts +++ b/components/input-number/nz-input-number.spec.ts @@ -11,8 +11,8 @@ import { NzInputNumberModule } from './nz-input-number.module'; describe('input number', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzInputNumberModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestInputNumberBasicComponent, NzTestInputNumberFormComponent ] + imports: [NzInputNumberModule, FormsModule, ReactiveFormsModule], + declarations: [NzTestInputNumberBasicComponent, NzTestInputNumberFormComponent] }); TestBed.compileComponents(); })); @@ -314,11 +314,11 @@ describe('input number', () => { }); it('should key up and down work with ctrl key', () => { const upArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowUp', + code: 'ArrowUp', ctrlKey: true }); const downArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowDown', + code: 'ArrowDown', ctrlKey: true }); fixture.detectChanges(); @@ -335,11 +335,11 @@ describe('input number', () => { }); it('should key up and down work with meta key', () => { const upArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowUp', + code: 'ArrowUp', metaKey: true }); const downArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowDown', + code: 'ArrowDown', metaKey: true }); fixture.detectChanges(); @@ -358,11 +358,11 @@ describe('input number', () => { testComponent.max = 100; testComponent.min = -100; const upArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowUp', + code: 'ArrowUp', shiftKey: true }); const downArrowEvent = new KeyboardEvent('keydown', { - code : 'ArrowDown', + code: 'ArrowDown', shiftKey: true }); fixture.detectChanges(); @@ -378,7 +378,7 @@ describe('input number', () => { fixture.detectChanges(); expect(testComponent.value).toBe(-10); }); - it('should update value immediately after formatter changed', (() => { + it('should update value immediately after formatter changed', () => { const newFormatter = (v: number) => `${v} %`; const initValue = 1; testComponent.nzInputNumberComponent.onModelChange(`${initValue}`); @@ -386,9 +386,9 @@ describe('input number', () => { testComponent.formatter = newFormatter; fixture.detectChanges(); expect(inputElement.value).toBe(newFormatter(initValue)); - })); + }); // #1449 - it('should up and down focus input', (() => { + it('should up and down focus input', () => { dispatchFakeEvent(upHandler, 'mousedown'); fixture.detectChanges(); expect(inputNumber.nativeElement.classList).toContain('ant-input-number-focused'); @@ -401,7 +401,7 @@ describe('input number', () => { dispatchFakeEvent(inputElement, 'blur'); fixture.detectChanges(); expect(inputNumber.nativeElement.classList).not.toContain('ant-input-number-focused'); - })); + }); }); describe('input number form', () => { @@ -460,7 +460,8 @@ describe('input number', () => { [nzStep]="step" [nzFormatter]="formatter" [nzParser]="parser" - [nzPrecision]="precision"> + [nzPrecision]="precision" + > ` }) @@ -475,7 +476,7 @@ export class NzTestInputNumberBasicComponent { placeholder = 'placeholder'; step = 1; precision?: number = 2; - formatter = (value: number) => value !== null ? `${value}` : ''; + formatter = (value: number) => (value !== null ? `${value}` : ''); parser = (value: number) => value; modelChange = jasmine.createSpy('change callback'); } @@ -493,7 +494,7 @@ export class NzTestInputNumberFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - inputNumber: [ 1 ] + inputNumber: [1] }); } diff --git a/components/input/demo/addon.ts b/components/input/demo/addon.ts index 1064c0adb21..a591b756907 100644 --- a/components/input/demo/addon.ts +++ b/components/input/demo/addon.ts @@ -5,12 +5,12 @@ import { Component } from '@angular/core'; template: `
- +
- + @@ -28,8 +28,8 @@ import { Component } from '@angular/core';
- - + +
` diff --git a/components/input/demo/autosize-textarea.ts b/components/input/demo/autosize-textarea.ts index 626a331bc42..4da84654f2f 100644 --- a/components/input/demo/autosize-textarea.ts +++ b/components/input/demo/autosize-textarea.ts @@ -6,9 +6,13 @@ import { Component } from '@angular/core';
- +
- ` }) export class NzDemoInputAutosizeTextareaComponent { diff --git a/components/input/demo/basic.ts b/components/input/demo/basic.ts index 28a2505bf2e..cc3864b6844 100644 --- a/components/input/demo/basic.ts +++ b/components/input/demo/basic.ts @@ -3,10 +3,10 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-input-basic', template: ` - -
-
- + +
+
+ ` }) export class NzDemoInputBasicComponent { diff --git a/components/input/demo/group.ts b/components/input/demo/group.ts index 879ba364d8c..a42d3fa8eed 100644 --- a/components/input/demo/group.ts +++ b/components/input/demo/group.ts @@ -5,40 +5,40 @@ import { Component } from '@angular/core'; template: `
- +
- +
-
+
- - + + -
+
- + -
+
- + -
+
- + -
+
@@ -49,25 +49,31 @@ import { Component } from '@angular/core'; -
+
- - - + + + -
+
- + -
+
@@ -78,33 +84,45 @@ import { Component } from '@angular/core'; ` }) export class NzDemoInputGroupComponent { - options = [{ - value: 'zhejiang', - label: 'Zhejiang', - children: [{ - value: 'hangzhou', - label: 'Hangzhou', - children: [{ - value: 'xihu', - label: 'West Lake', - isLeaf: true - }] - }, { - value: 'ningbo', - label: 'Ningbo', - isLeaf: true - }] - }, { - value: 'jiangsu', - label: 'Jiangsu', - children: [{ - value: 'nanjing', - label: 'Nanjing', - children: [{ - value: 'zhonghuamen', - label: 'Zhong Hua Men', - isLeaf: true - }] - }] - }]; + options = [ + { + value: 'zhejiang', + label: 'Zhejiang', + children: [ + { + value: 'hangzhou', + label: 'Hangzhou', + children: [ + { + value: 'xihu', + label: 'West Lake', + isLeaf: true + } + ] + }, + { + value: 'ningbo', + label: 'Ningbo', + isLeaf: true + } + ] + }, + { + value: 'jiangsu', + label: 'Jiangsu', + children: [ + { + value: 'nanjing', + label: 'Nanjing', + children: [ + { + value: 'zhonghuamen', + label: 'Zhong Hua Men', + isLeaf: true + } + ] + } + ] + } + ]; } diff --git a/components/input/demo/password-input.ts b/components/input/demo/password-input.ts index c63c082a953..46daf3f6e8b 100644 --- a/components/input/demo/password-input.ts +++ b/components/input/demo/password-input.ts @@ -4,14 +4,19 @@ import { Component } from '@angular/core'; selector: 'nz-demo-input-password-input', template: ` - + - + `, - styles : [ - ` + styles: [ + ` i { cursor: pointer; } diff --git a/components/input/demo/presuffix.ts b/components/input/demo/presuffix.ts index e95eddd3b0b..c61cd78cc56 100644 --- a/components/input/demo/presuffix.ts +++ b/components/input/demo/presuffix.ts @@ -4,13 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-input-presuffix', template: ` - + - + `, - styles : [ - ` + styles: [ + ` .anticon-close-circle { cursor: pointer; color: #ccc; diff --git a/components/input/demo/search-input.ts b/components/input/demo/search-input.ts index 258678ad480..a3ff76903ce 100644 --- a/components/input/demo/search-input.ts +++ b/components/input/demo/search-input.ts @@ -4,28 +4,27 @@ import { Component } from '@angular/core'; selector: 'nz-demo-input-search-input', template: ` - + -
-
+
+
- + -
-
+
+
- + ` }) -export class NzDemoInputSearchInputComponent { -} +export class NzDemoInputSearchInputComponent {} diff --git a/components/input/demo/size.ts b/components/input/demo/size.ts index 2b13a210491..69fdc169ea9 100644 --- a/components/input/demo/size.ts +++ b/components/input/demo/size.ts @@ -4,13 +4,13 @@ import { Component } from '@angular/core'; selector: 'nz-demo-input-size', template: `
- - - + + +
`, - styles : [ - ` + styles: [ + ` .example-input .ant-input { width: 200px; margin: 0 8px 8px 0; @@ -18,5 +18,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoInputSizeComponent { -} +export class NzDemoInputSizeComponent {} diff --git a/components/input/demo/tooltip.ts b/components/input/demo/tooltip.ts index a2aac0b7f4f..19c62c5b7ac 100644 --- a/components/input/demo/tooltip.ts +++ b/components/input/demo/tooltip.ts @@ -1,15 +1,24 @@ import { Component, ElementRef, ViewChild, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-input-tooltip', + selector: 'nz-demo-input-tooltip', encapsulation: ViewEncapsulation.None, - template : ` + template: ` - + `, - styles : [ - ` + styles: [ + ` .numeric-input .ant-tooltip-inner { min-width: 32px; min-height: 37px; @@ -18,7 +27,6 @@ import { Component, ElementRef, ViewChild, ViewEncapsulation } from '@angular/co .numeric-input .numeric-input-title { font-size: 14px; } - ` ] }) @@ -55,8 +63,8 @@ export class NzDemoInputTooltipComponent { formatNumber(value: string): string { const string = `${value}`; const list = string.split('.'); - const prefix = list[ 0 ].charAt(0) === '-' ? '-' : ''; - let num = prefix ? list[ 0 ].slice(1) : list[ 0 ]; + const prefix = list[0].charAt(0) === '-' ? '-' : ''; + let num = prefix ? list[0].slice(1) : list[0]; let result = ''; while (num.length > 3) { result = `,${num.slice(-3)}${result}`; @@ -65,7 +73,6 @@ export class NzDemoInputTooltipComponent { if (num) { result = num + result; } - return `${prefix}${result}${list[ 1 ] ? `.${list[ 1 ]}` : ''}`; + return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`; } - } diff --git a/components/input/nz-autosize.directive.ts b/components/input/nz-autosize.directive.ts index ddd721c6f1d..0892e7f5fc2 100644 --- a/components/input/nz-autosize.directive.ts +++ b/components/input/nz-autosize.directive.ts @@ -1,13 +1,5 @@ import { Platform } from '@angular/cdk/platform'; -import { - AfterViewInit, - Directive, - DoCheck, - ElementRef, - Input, - NgZone, - OnDestroy -} from '@angular/core'; +import { AfterViewInit, Directive, DoCheck, ElementRef, Input, NgZone, OnDestroy } from '@angular/core'; import { fromEvent, Subject } from 'rxjs'; import { auditTime, takeUntil } from 'rxjs/operators'; @@ -22,10 +14,10 @@ export function isAutoSizeType(value: string | boolean | AutoSizeType): value is @Directive({ selector: 'textarea[nzAutosize]', - host : { + host: { // Textarea elements that have the directive applied should have a single row by default. // Browsers normally show two rows by default and therefore this limits the minRows binding. - 'rows' : '1', + rows: '1', '(input)': 'noopInputHandler()' } }) @@ -82,7 +74,9 @@ export class NzAutosizeDirective implements AfterViewInit, OnDestroy, DoCheck { // need to be removed temporarily. textarea.classList.add('cdk-textarea-autosize-measuring'); textarea.placeholder = ''; - const height = Math.round((textarea.scrollHeight - this.inputGap) / this.cachedLineHeight) * this.cachedLineHeight + this.inputGap; + const height = + Math.round((textarea.scrollHeight - this.inputGap) / this.cachedLineHeight) * this.cachedLineHeight + + this.inputGap; // Use the scrollHeight to know how large the textarea *would* be if fit its entire value. textarea.style.height = `${height}px`; @@ -92,19 +86,21 @@ export class NzAutosizeDirective implements AfterViewInit, OnDestroy, DoCheck { // On Firefox resizing the textarea will prevent it from scrolling to the caret position. // We need to re-set the selection in order for it to scroll to the proper position. if (typeof requestAnimationFrame !== 'undefined') { - this.ngZone.runOutsideAngular(() => requestAnimationFrame(() => { - const { selectionStart, selectionEnd } = textarea; - - // IE will throw an "Unspecified error" if we try to set the selection range after the - // element has been removed from the DOM. Assert that the directive hasn't been destroyed - // between the time we requested the animation frame and when it was executed. - // Also note that we have to assert that the textarea is focused before we set the - // selection range. Setting the selection range on a non-focused textarea will cause - // it to receive focus on IE and Edge. - if (!this.destroy$.isStopped && document.activeElement === textarea) { - textarea.setSelectionRange(selectionStart, selectionEnd); - } - })); + this.ngZone.runOutsideAngular(() => + requestAnimationFrame(() => { + const { selectionStart, selectionEnd } = textarea; + + // IE will throw an "Unspecified error" if we try to set the selection range after the + // element has been removed from the DOM. Assert that the directive hasn't been destroyed + // between the time we requested the animation frame and when it was executed. + // Also note that we have to assert that the textarea is focused before we set the + // selection range. Setting the selection range on a non-focused textarea will cause + // it to receive focus on IE and Edge. + if (!this.destroy$.isStopped && document.activeElement === textarea) { + textarea.setSelectionRange(selectionStart, selectionEnd); + } + }) + ); } this.previousValue = value; @@ -148,8 +144,8 @@ export class NzAutosizeDirective implements AfterViewInit, OnDestroy, DoCheck { } setMinHeight(): void { - const minHeight = this.minRows && this.cachedLineHeight ? - `${this.minRows * this.cachedLineHeight + this.inputGap}px` : null; + const minHeight = + this.minRows && this.cachedLineHeight ? `${this.minRows * this.cachedLineHeight + this.inputGap}px` : null; if (minHeight) { this.el.style.minHeight = minHeight; @@ -157,8 +153,8 @@ export class NzAutosizeDirective implements AfterViewInit, OnDestroy, DoCheck { } setMaxHeight(): void { - const maxHeight = this.maxRows && this.cachedLineHeight ? - `${this.maxRows * this.cachedLineHeight + this.inputGap}px` : null; + const maxHeight = + this.maxRows && this.cachedLineHeight ? `${this.maxRows * this.cachedLineHeight + this.inputGap}px` : null; if (maxHeight) { this.el.style.maxHeight = maxHeight; @@ -169,18 +165,18 @@ export class NzAutosizeDirective implements AfterViewInit, OnDestroy, DoCheck { // no-op handler that ensures we're running change detection on input events. } - constructor(private elementRef: ElementRef, - private ngZone: NgZone, - private platform: Platform) { - } + constructor(private elementRef: ElementRef, private ngZone: NgZone, private platform: Platform) {} ngAfterViewInit(): void { if (this.nzAutosize && this.platform.isBrowser) { this.resizeToFitContent(); this.ngZone.runOutsideAngular(() => { fromEvent(window, 'resize') - .pipe(auditTime(16), takeUntil(this.destroy$)) - .subscribe(() => this.resizeToFitContent(true)); + .pipe( + auditTime(16), + takeUntil(this.destroy$) + ) + .subscribe(() => this.resizeToFitContent(true)); }); } } diff --git a/components/input/nz-autosize.spec.ts b/components/input/nz-autosize.spec.ts index 04d55d0a6a0..dfea91ed308 100644 --- a/components/input/nz-autosize.spec.ts +++ b/components/input/nz-autosize.spec.ts @@ -9,9 +9,9 @@ import { NzInputModule } from './nz-input.module'; describe('autoresize', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzInputModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestInputWithTextAreaAutoSizeStringComponent, NzTestInputWithTextAreaAutoSizeObjectComponent ], - providers : [] + imports: [NzInputModule, FormsModule, ReactiveFormsModule], + declarations: [NzTestInputWithTextAreaAutoSizeStringComponent, NzTestInputWithTextAreaAutoSizeObjectComponent], + providers: [] }).compileComponents(); })); @@ -44,10 +44,11 @@ describe('autoresize', () => { flush(); autosize.resizeToFitContent(); - expect(textarea.clientHeight) - .toBeGreaterThan(previousHeight, 'Expected textarea to have grown with added content.'); - expect(textarea.clientHeight) - .toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); + expect(textarea.clientHeight).toBeGreaterThan( + previousHeight, + 'Expected textarea to have grown with added content.' + ); + expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); previousHeight = textarea.clientHeight; testComponent.value += ` @@ -61,10 +62,11 @@ describe('autoresize', () => { flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); - expect(textarea.clientHeight) - .toBeGreaterThan(previousHeight, 'Expected textarea to have grown with added content.'); - expect(textarea.clientHeight) - .toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); + expect(textarea.clientHeight).toBeGreaterThan( + previousHeight, + 'Expected textarea to have grown with added content.' + ); + expect(textarea.clientHeight).toBe(textarea.scrollHeight, 'Expected textarea height to match its scrollHeight'); })); it('should trigger a resize when the window is resized', fakeAsync(() => { @@ -90,7 +92,6 @@ describe('autoresize', () => { autosize = fixture.debugElement.query(By.directive(NzAutosizeDirective)).injector.get(NzAutosizeDirective); }); it('should set a min-height based on minRows', fakeAsync(() => { - autosize.resizeToFitContent(true); fixture.detectChanges(); flush(); @@ -101,8 +102,10 @@ describe('autoresize', () => { flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); - expect(parseInt(textarea.style.minHeight as string, 10)) - .toBeGreaterThan(previousMinHeight, 'Expected increased min-height with minRows increase.'); + expect(parseInt(textarea.style.minHeight as string, 10)).toBeGreaterThan( + previousMinHeight, + 'Expected increased min-height with minRows increase.' + ); })); it('should set a max-height based on maxRows', fakeAsync(() => { @@ -116,19 +119,23 @@ describe('autoresize', () => { flush(); fixture.detectChanges(); autosize.resizeToFitContent(true); - expect(parseInt(textarea.style.maxHeight as string, 10)) - .toBeGreaterThan(previousMaxHeight, 'Expected increased max-height with maxRows increase.'); + expect(parseInt(textarea.style.maxHeight as string, 10)).toBeGreaterThan( + previousMaxHeight, + 'Expected increased max-height with maxRows increase.' + ); })); }); }); }); @Component({ - selector : 'nz-test-input-with-textarea-autosize-string', - template : ``, + selector: 'nz-test-input-with-textarea-autosize-string', + template: ` + + `, encapsulation: ViewEncapsulation.None, - styles : [ - ` + styles: [ + ` textarea.cdk-textarea-autosize-measuring { height: auto !important; overflow: hidden !important; @@ -143,11 +150,13 @@ export class NzTestInputWithTextAreaAutoSizeStringComponent { } @Component({ - selector : 'nz-test-input-with-textarea-autosize-object', - template : ``, + selector: 'nz-test-input-with-textarea-autosize-object', + template: ` + + `, encapsulation: ViewEncapsulation.None, - styles : [ - ` + styles: [ + ` textarea.cdk-textarea-autosize-measuring { height: auto !important; overflow: hidden !important; diff --git a/components/input/nz-input-group.component.ts b/components/input/nz-input-group.component.ts index 71b8e21e3b2..c07fae71152 100644 --- a/components/input/nz-input-group.component.ts +++ b/components/input/nz-input-group.component.ts @@ -14,29 +14,28 @@ import { InputBoolean } from '../core/util/convert'; import { NzInputDirective } from './nz-input.directive'; @Component({ - selector : 'nz-input-group', + selector: 'nz-input-group', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-input-group.component.html', - host : { - '[class.ant-input-group-compact]' : 'nzCompact', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-input-group.component.html', + host: { + '[class.ant-input-group-compact]': 'nzCompact', '[class.ant-input-search-enter-button]': 'nzSearch', - '[class.ant-input-search]' : 'nzSearch', - '[class.ant-input-search-sm]' : 'isSmallSearch', - '[class.ant-input-affix-wrapper]' : 'isAffixWrapper', - '[class.ant-input-group-wrapper]' : 'isAddOn', - '[class.ant-input-group]' : 'isGroup', - '[class.ant-input-group-lg]' : 'isLargeGroup', - '[class.ant-input-group-wrapper-lg]' : 'isLargeGroupWrapper', - '[class.ant-input-affix-wrapper-lg]' : 'isLargeAffix', - '[class.ant-input-search-lg]' : 'isLargeSearch', - '[class.ant-input-group-sm]' : 'isSmallGroup', - '[class.ant-input-affix-wrapper-sm]' : 'isSmallAffix', - '[class.ant-input-group-wrapper-sm]' : 'isSmallGroupWrapper' + '[class.ant-input-search]': 'nzSearch', + '[class.ant-input-search-sm]': 'isSmallSearch', + '[class.ant-input-affix-wrapper]': 'isAffixWrapper', + '[class.ant-input-group-wrapper]': 'isAddOn', + '[class.ant-input-group]': 'isGroup', + '[class.ant-input-group-lg]': 'isLargeGroup', + '[class.ant-input-group-wrapper-lg]': 'isLargeGroupWrapper', + '[class.ant-input-affix-wrapper-lg]': 'isLargeAffix', + '[class.ant-input-search-lg]': 'isLargeSearch', + '[class.ant-input-group-sm]': 'isSmallGroup', + '[class.ant-input-affix-wrapper-sm]': 'isSmallAffix', + '[class.ant-input-group-wrapper-sm]': 'isSmallGroupWrapper' } }) - export class NzInputGroupComponent implements AfterContentInit { @ContentChildren(NzInputDirective) listOfNzInputDirective: QueryList; private _size: NzSizeLDSType = 'default'; @@ -69,7 +68,7 @@ export class NzInputGroupComponent implements AfterContentInit { } get isAffix(): boolean { - return (!!(this.nzSuffix || this.nzPrefix || this.nzPrefixIcon || this.nzSuffixIcon)); + return !!(this.nzSuffix || this.nzPrefix || this.nzPrefixIcon || this.nzSuffixIcon); } get isAddOn(): boolean { @@ -81,7 +80,7 @@ export class NzInputGroupComponent implements AfterContentInit { } get isGroup(): boolean { - return (!this.isAffix) && (!this.isAddOn); + return !this.isAffix && !this.isAddOn; } get isLargeGroup(): boolean { @@ -118,7 +117,7 @@ export class NzInputGroupComponent implements AfterContentInit { updateChildrenInputSize(): void { if (this.listOfNzInputDirective) { - this.listOfNzInputDirective.forEach(item => item.nzSize = this.nzSize); + this.listOfNzInputDirective.forEach(item => (item.nzSize = this.nzSize)); } } diff --git a/components/input/nz-input-group.spec.ts b/components/input/nz-input-group.spec.ts index 047e099c5b8..ba87715ca5e 100644 --- a/components/input/nz-input-group.spec.ts +++ b/components/input/nz-input-group.spec.ts @@ -9,9 +9,15 @@ import { NzInputModule } from './nz-input.module'; describe('input-group', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzInputModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ NzTestInputGroupAddonComponent, NzTestInputGroupAffixComponent, NzTestInputGroupMultipleComponent, NzTestInputGroupColComponent, NzTestInputGroupMixComponent ], - providers : [] + imports: [NzInputModule, FormsModule, ReactiveFormsModule, NzIconTestModule], + declarations: [ + NzTestInputGroupAddonComponent, + NzTestInputGroupAffixComponent, + NzTestInputGroupMultipleComponent, + NzTestInputGroupColComponent, + NzTestInputGroupMixComponent + ], + providers: [] }).compileComponents(); })); describe('input group', () => { @@ -44,7 +50,9 @@ describe('input-group', () => { expect(inputGroupElement.firstElementChild!.classList).toContain('ant-input-group'); expect(inputGroupElement.firstElementChild!.children.length).toBe(2); expect(inputGroupElement.firstElementChild!.lastElementChild!.classList).toContain('ant-input'); - expect((inputGroupElement.firstElementChild!.firstElementChild as HTMLElement).innerText).toBe('beforeTemplate'); + expect((inputGroupElement.firstElementChild!.firstElementChild as HTMLElement).innerText).toBe( + 'beforeTemplate' + ); }); it('should after content string work', () => { testComponent.afterContent = 'after'; @@ -205,7 +213,9 @@ describe('input-group', () => { inputGroupElement = fixture.debugElement.query(By.directive(NzInputGroupComponent)).nativeElement; }); it('should mix work', () => { - expect(inputGroupElement.querySelector('.ant-input-affix-wrapper')!.nextElementSibling!.classList).toContain('ant-input-group-addon'); + expect(inputGroupElement.querySelector('.ant-input-affix-wrapper')!.nextElementSibling!.classList).toContain( + 'ant-input-group-addon' + ); }); }); }); @@ -215,7 +225,7 @@ describe('input-group', () => { selector: 'nz-test-input-group-addon', template: ` - + beforeTemplate afterTemplate @@ -233,7 +243,7 @@ export class NzTestInputGroupAddonComponent { selector: 'nz-test-input-group-affix', template: ` - + beforeTemplate afterTemplate @@ -251,8 +261,8 @@ export class NzTestInputGroupAffixComponent { selector: 'nz-test-input-group-multiple', template: ` - - + + ` }) @@ -267,25 +277,23 @@ export class NzTestInputGroupMultipleComponent { selector: 'nz-test-input-group-mix', template: ` - + ` }) -export class NzTestInputGroupMixComponent { -} +export class NzTestInputGroupMixComponent {} @Component({ selector: 'nz-test-input-group-col', template: `
- +
- +
` }) -export class NzTestInputGroupColComponent { -} +export class NzTestInputGroupColComponent {} diff --git a/components/input/nz-input.directive.ts b/components/input/nz-input.directive.ts index 170c734fa62..27bc1dc1522 100644 --- a/components/input/nz-input.directive.ts +++ b/components/input/nz-input.directive.ts @@ -1,19 +1,14 @@ -import { - Directive, ElementRef, - Input, - Optional, Renderer2, - Self -} from '@angular/core'; +import { Directive, ElementRef, Input, Optional, Renderer2, Self } from '@angular/core'; import { NgControl } from '@angular/forms'; import { NzSizeLDSType } from '../core/types/size'; import { toBoolean } from '../core/util/convert'; @Directive({ selector: '[nz-input]', - host : { + host: { '[class.ant-input-disabled]': 'disabled', - '[class.ant-input-lg]' : `nzSize === 'large'`, - '[class.ant-input-sm]' : `nzSize === 'small'` + '[class.ant-input-lg]': `nzSize === 'large'`, + '[class.ant-input-sm]': `nzSize === 'small'` } }) export class NzInputDirective { diff --git a/components/input/nz-input.module.ts b/components/input/nz-input.module.ts index 662a676eb17..56386e1a798 100644 --- a/components/input/nz-input.module.ts +++ b/components/input/nz-input.module.ts @@ -15,5 +15,4 @@ import { NzInputDirective } from './nz-input.directive'; exports : [ NzInputDirective, NzInputGroupComponent, NzAutosizeDirective ], imports : [ CommonModule, FormsModule, NzIconModule, PlatformModule, NzAddOnModule ] }) -export class NzInputModule { -} +export class NzInputModule {} diff --git a/components/input/nz-input.spec.ts b/components/input/nz-input.spec.ts index 816040d3c9f..fce36c420be 100644 --- a/components/input/nz-input.spec.ts +++ b/components/input/nz-input.spec.ts @@ -9,9 +9,9 @@ import { NzInputModule } from './nz-input.module'; describe('input', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzInputModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ NzTestInputWithInputComponent, NzTestInputWithTextAreaComponent, NzTestInputFormComponent ], - providers : [] + imports: [NzInputModule, FormsModule, ReactiveFormsModule, NzIconTestModule], + declarations: [NzTestInputWithInputComponent, NzTestInputWithTextAreaComponent, NzTestInputFormComponent], + providers: [] }).compileComponents(); })); describe('single input', () => { @@ -92,7 +92,9 @@ describe('input', () => { @Component({ selector: 'nz-test-input-with-input', - template: `` + template: ` + + ` }) export class NzTestInputWithInputComponent { size = 'default'; @@ -101,16 +103,17 @@ export class NzTestInputWithInputComponent { @Component({ selector: 'nz-test-input-with-textarea', - template: `` + template: ` + + ` }) -export class NzTestInputWithTextAreaComponent { -} +export class NzTestInputWithTextAreaComponent {} @Component({ selector: 'nz-test-input-form', template: `
- +
` }) @@ -119,7 +122,7 @@ export class NzTestInputFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - input: [ 'abc' ] + input: ['abc'] }); } diff --git a/components/layout/demo/basic.ts b/components/layout/demo/basic.ts index e05a4d579c2..d72ee9560a8 100644 --- a/components/layout/demo/basic.ts +++ b/components/layout/demo/basic.ts @@ -36,41 +36,43 @@ import { Component } from '@angular/core'; `, - styles : [ ` - :host { - text-align: center; - } + styles: [ + ` + :host { + text-align: center; + } - nz-header,nz-footer { - background: #7dbcea; - color: #fff; - } + nz-header, + nz-footer { + background: #7dbcea; + color: #fff; + } - nz-footer { - line-height: 1.5; - } + nz-footer { + line-height: 1.5; + } - nz-sider { - background: #3ba0e9; - color: #fff; - line-height: 120px; - } + nz-sider { + background: #3ba0e9; + color: #fff; + line-height: 120px; + } - nz-content { - background: rgba(16, 142, 233, 1); - color: #fff; - min-height: 120px; - line-height: 120px; - } + nz-content { + background: rgba(16, 142, 233, 1); + color: #fff; + min-height: 120px; + line-height: 120px; + } - nz-layout { - margin-bottom: 48px; - } + nz-layout { + margin-bottom: 48px; + } - nz-layout:last-child { - margin: 0; - } - ` ] + nz-layout:last-child { + margin: 0; + } + ` + ] }) -export class NzDemoLayoutBasicComponent { -} +export class NzDemoLayoutBasicComponent {} diff --git a/components/layout/demo/custom-trigger.ts b/components/layout/demo/custom-trigger.ts index 69254d4f406..8c7a97e05b4 100644 --- a/components/layout/demo/custom-trigger.ts +++ b/components/layout/demo/custom-trigger.ts @@ -5,8 +5,7 @@ import { Component, TemplateRef, ViewChild } from '@angular/core'; template: ` - +
  • User @@ -23,12 +22,19 @@ import { Component, TemplateRef, ViewChild } from '@angular/core';
  • Team 2
-
  • File
  • +
  • + File +
  • - + @@ -46,14 +52,14 @@ import { Component, TemplateRef, ViewChild } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` .trigger { font-size: 18px; line-height: 64px; padding: 0 24px; cursor: pointer; - transition: color .3s; + transition: color 0.3s; } .trigger:hover { @@ -62,7 +68,7 @@ import { Component, TemplateRef, ViewChild } from '@angular/core'; .logo { height: 32px; - background: rgba(255, 255, 255, .2); + background: rgba(255, 255, 255, 0.2); margin: 16px; } ` diff --git a/components/layout/demo/fixed-sider.ts b/components/layout/demo/fixed-sider.ts index 45599ba027a..0304d6fa861 100644 --- a/components/layout/demo/fixed-sider.ts +++ b/components/layout/demo/fixed-sider.ts @@ -5,49 +5,64 @@ import { Component } from '@angular/core'; template: ` - +
      -
    • nav 1
    • -
    • nav 2
    • -
    • nav 3
    • -
    • nav 4
    • -
    • nav 5
    • -
    • nav 6
    • -
    • nav 7
    • -
    • nav 8
    • +
    • + nav 1 +
    • +
    • + nav 2 +
    • +
    • + nav 3 +
    • +
    • + nav 4 +
    • +
    • + nav 5 +
    • +
    • + nav 6 +
    • +
    • + nav 7 +
    • +
    • + nav 8 +
    -
    - ... -
    - Really -
    ...
    ...
    ...
    - long -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    ... -
    ...
    ...
    ...
    ...
    ...
    - content -
    +
    + ... +
    + Really +
    ...
    ...
    ...
    + long +
    ...
    ...
    ...
    ...
    ...
    ... +
    ...
    ...
    ...
    ...
    ...
    ... +
    ...
    ...
    ...
    ...
    ...
    ... +
    ...
    ...
    ...
    ...
    ...
    ... +
    ...
    ...
    ...
    ...
    ...
    ... +
    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...
    ...
    + content +
    Ant Design ©2019 Implement By Angular
    `, - styles : [ ` + styles: [ + ` .logo { height: 32px; - background: rgba(255,255,255,.2); + background: rgba(255, 255, 255, 0.2); margin: 16px; } - ` ] + ` + ] }) -export class NzDemoLayoutFixedSiderComponent { -} +export class NzDemoLayoutFixedSiderComponent {} diff --git a/components/layout/demo/fixed.ts b/components/layout/demo/fixed.ts index 4bcfca8740f..780450040ad 100644 --- a/components/layout/demo/fixed.ts +++ b/components/layout/demo/fixed.ts @@ -23,15 +23,16 @@ import { Component } from '@angular/core'; Ant Design ©2019 Implement By Angular
    `, - styles : [ ` - .logo { - width: 120px; - height: 31px; - background: rgba(255,255,255,.2); - margin: 16px 24px 16px 0; - float: left; - } - ` ] + styles: [ + ` + .logo { + width: 120px; + height: 31px; + background: rgba(255, 255, 255, 0.2); + margin: 16px 24px 16px 0; + float: left; + } + ` + ] }) -export class NzDemoLayoutFixedComponent { -} +export class NzDemoLayoutFixedComponent {} diff --git a/components/layout/demo/responsive.ts b/components/layout/demo/responsive.ts index e135026e1d6..954f2140794 100644 --- a/components/layout/demo/responsive.ts +++ b/components/layout/demo/responsive.ts @@ -4,15 +4,27 @@ import { Component } from '@angular/core'; selector: 'nz-demo-layout-responsive', template: ` - - + +
      -
    • nav 1
    • -
    • nav 2 +
    • + nav 1 +
    • +
    • + nav 2 +
    • +
    • + nav 3 +
    • +
    • + nav 4
    • -
    • nav 3
    • -
    • nav 4
    @@ -29,11 +41,11 @@ import { Component } from '@angular/core'; `, - styles : [ + styles: [ ` .logo { height: 32px; - background: rgba(255,255,255,.2); + background: rgba(255, 255, 255, 0.2); margin: 16px; } ` diff --git a/components/layout/demo/side.ts b/components/layout/demo/side.ts index 2d897725318..1647b9cef84 100644 --- a/components/layout/demo/side.ts +++ b/components/layout/demo/side.ts @@ -5,8 +5,7 @@ import { Component } from '@angular/core'; template: ` - +
    • User @@ -23,7 +22,9 @@ import { Component } from '@angular/core';
    • Team 2
    -
  • File
  • +
  • + File +
  • @@ -41,11 +42,11 @@ import { Component } from '@angular/core';
    `, - styles : [ - ` + styles: [ + ` .logo { height: 32px; - background: rgba(255, 255, 255, .2); + background: rgba(255, 255, 255, 0.2); margin: 16px; } ` diff --git a/components/layout/demo/top-side-2.ts b/components/layout/demo/top-side-2.ts index 4091b14ef0c..18c9cd6864e 100644 --- a/components/layout/demo/top-side-2.ts +++ b/components/layout/demo/top-side-2.ts @@ -55,14 +55,16 @@ import { Component } from '@angular/core';
    `, - styles : [ - `.logo { - width: 120px; - height: 31px; - background: rgba(255,255,255,.2); - margin: 16px 28px 16px 0; - float: left; - }` + styles: [ + ` + .logo { + width: 120px; + height: 31px; + background: rgba(255, 255, 255, 0.2); + margin: 16px 28px 16px 0; + float: left; + } + ` ] }) -export class NzDemoLayoutTopSide2Component { } +export class NzDemoLayoutTopSide2Component {} diff --git a/components/layout/demo/top-side.ts b/components/layout/demo/top-side.ts index 1a03c2634c1..b50313fe4d9 100644 --- a/components/layout/demo/top-side.ts +++ b/components/layout/demo/top-side.ts @@ -56,14 +56,16 @@ import { Component } from '@angular/core';
    `, - styles : [ - `.logo { - width: 120px; - height: 31px; - background: rgba(255,255,255,.2); - margin: 16px 28px 16px 0; - float: left; - }` + styles: [ + ` + .logo { + width: 120px; + height: 31px; + background: rgba(255, 255, 255, 0.2); + margin: 16px 28px 16px 0; + float: left; + } + ` ] }) -export class NzDemoLayoutTopSideComponent { } +export class NzDemoLayoutTopSideComponent {} diff --git a/components/layout/demo/top.ts b/components/layout/demo/top.ts index 42139636188..453d5a87747 100644 --- a/components/layout/demo/top.ts +++ b/components/layout/demo/top.ts @@ -23,15 +23,16 @@ import { Component } from '@angular/core'; Ant Design ©2019 Implement By Angular `, - styles : [ - `.logo { - width: 120px; - height: 31px; - background: rgba(255,255,255,.2); - margin: 16px 24px 16px 0; - float: left; - } + styles: [ + ` + .logo { + width: 120px; + height: 31px; + background: rgba(255, 255, 255, 0.2); + margin: 16px 24px 16px 0; + float: left; + } ` ] }) -export class NzDemoLayoutTopComponent { } +export class NzDemoLayoutTopComponent {} diff --git a/components/layout/nz-content.component.ts b/components/layout/nz-content.component.ts index 3519857425f..c46be94df7f 100644 --- a/components/layout/nz-content.component.ts +++ b/components/layout/nz-content.component.ts @@ -1,15 +1,17 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-content', + selector: 'nz-content', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-content.component.html', - styles : [ - `nz-content { - display: block; - }` + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-content.component.html', + styles: [ + ` + nz-content { + display: block; + } + ` ] }) export class NzContentComponent { diff --git a/components/layout/nz-footer.component.ts b/components/layout/nz-footer.component.ts index cdd96640655..0a825ebe087 100644 --- a/components/layout/nz-footer.component.ts +++ b/components/layout/nz-footer.component.ts @@ -1,15 +1,17 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-footer', + selector: 'nz-footer', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-footer.component.html', - styles : [ - `nz-footer { - display: block; - }` + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-footer.component.html', + styles: [ + ` + nz-footer { + display: block; + } + ` ] }) export class NzFooterComponent { diff --git a/components/layout/nz-header.component.ts b/components/layout/nz-header.component.ts index 2fca0ec9233..0aa693976a9 100644 --- a/components/layout/nz-header.component.ts +++ b/components/layout/nz-header.component.ts @@ -1,15 +1,17 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-header', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: 'nz-header', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - templateUrl : './nz-header.component.html', - styles : [ - `nz-header { - display: block; - }` + templateUrl: './nz-header.component.html', + styles: [ + ` + nz-header { + display: block; + } + ` ] }) export class NzHeaderComponent { diff --git a/components/layout/nz-layout.component.ts b/components/layout/nz-layout.component.ts index ad080de4325..70750ed6522 100644 --- a/components/layout/nz-layout.component.ts +++ b/components/layout/nz-layout.component.ts @@ -1,14 +1,13 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-layout', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, + selector: 'nz-layout', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, - templateUrl : './nz-layout.component.html' + templateUrl: './nz-layout.component.html' }) export class NzLayoutComponent { - destroySider(): void { this.renderer.removeClass(this.elementRef.nativeElement, 'ant-layout-has-sider'); } diff --git a/components/layout/nz-layout.module.ts b/components/layout/nz-layout.module.ts index ab61eb47c97..2b00dcc2a70 100644 --- a/components/layout/nz-layout.module.ts +++ b/components/layout/nz-layout.module.ts @@ -11,9 +11,8 @@ import { NzLayoutComponent } from './nz-layout.component'; import { NzSiderComponent } from './nz-sider.component'; @NgModule({ - declarations: [ NzLayoutComponent, NzHeaderComponent, NzContentComponent, NzFooterComponent, NzSiderComponent ], - exports : [ NzLayoutComponent, NzHeaderComponent, NzContentComponent, NzFooterComponent, NzSiderComponent ], - imports : [ CommonModule, NzIconModule, LayoutModule, PlatformModule ] + declarations: [NzLayoutComponent, NzHeaderComponent, NzContentComponent, NzFooterComponent, NzSiderComponent], + exports: [NzLayoutComponent, NzHeaderComponent, NzContentComponent, NzFooterComponent, NzSiderComponent], + imports: [CommonModule, NzIconModule, LayoutModule, PlatformModule] }) -export class NzLayoutModule { -} +export class NzLayoutModule {} diff --git a/components/layout/nz-layout.spec.ts b/components/layout/nz-layout.spec.ts index 83d61165eaa..20d162b27ab 100644 --- a/components/layout/nz-layout.spec.ts +++ b/components/layout/nz-layout.spec.ts @@ -26,9 +26,9 @@ describe('layout', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzLayoutModule ], - declarations: [ NzDemoLayoutBasicComponent ], - providers : [] + imports: [NzLayoutModule], + declarations: [NzDemoLayoutBasicComponent], + providers: [] }).compileComponents(); })); @@ -48,10 +48,15 @@ describe('layout', () => { expect(contents.every(content => content.nativeElement.classList.contains('ant-layout-content'))).toBe(true); expect(footers.every(footer => footer.nativeElement.classList.contains('ant-layout-footer'))).toBe(true); expect(siders.every(sider => sider.nativeElement.classList.contains('ant-layout-sider'))).toBe(true); - expect(siders.every(sider => sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;')).toBe(true); - expect(layouts[ 2 ].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); - expect(layouts[ 4 ].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); - expect(layouts[ 5 ].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); + expect( + siders.every( + sider => + sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;' + ) + ).toBe(true); + expect(layouts[2].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); + expect(layouts[4].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); + expect(layouts[5].nativeElement.classList.contains('ant-layout-has-sider')).toBe(true); }); }); describe('side', () => { @@ -62,10 +67,10 @@ describe('layout', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzLayoutModule ], - declarations: [ NzDemoLayoutSideComponent ], - providers : [], - schemas : [ NO_ERRORS_SCHEMA ] + imports: [NzLayoutModule], + declarations: [NzDemoLayoutSideComponent], + providers: [], + schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); @@ -79,25 +84,35 @@ describe('layout', () => { testComponent.isCollapsed = false; fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.ant-layout-sider-trigger')); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 200px;').toBe(true); trigger.nativeElement.click(); fixture.detectChanges(); expect(testComponent.isCollapsed).toBe(true); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 80px;').toBe(true); trigger.nativeElement.click(); fixture.detectChanges(); expect(testComponent.isCollapsed).toBe(false); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 200px;').toBe(true); testComponent.isCollapsed = true; fixture.detectChanges(); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 80px;').toBe(true); testComponent.isCollapsed = false; fixture.detectChanges(); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 200px; max-width: 200px; min-width: 200px; width: 200px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 200px;').toBe(true); }); it('should nzWidth work', () => { @@ -105,25 +120,35 @@ describe('layout', () => { testComponent.width = 300; fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.ant-layout-sider-trigger')); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 300px;').toBe(true); trigger.nativeElement.click(); fixture.detectChanges(); expect(testComponent.isCollapsed).toBe(true); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 80px;').toBe(true); trigger.nativeElement.click(); fixture.detectChanges(); expect(testComponent.isCollapsed).toBe(false); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 300px;').toBe(true); testComponent.isCollapsed = true; fixture.detectChanges(); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 80px; max-width: 80px; min-width: 80px; width: 80px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 80px;').toBe(true); testComponent.isCollapsed = false; fixture.detectChanges(); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;').toBe(true); + expect( + sider.nativeElement.style.cssText === 'flex: 0 0 300px; max-width: 300px; min-width: 300px; width: 300px;' + ).toBe(true); expect(trigger.nativeElement.style.cssText === 'width: 300px;').toBe(true); }); @@ -142,7 +167,6 @@ describe('layout', () => { testComponent.isCollapsed = true; fixture.detectChanges(); expect(trigger.nativeElement.firstElementChild!.classList.contains('anticon-left')).toBe(true); - }); }); describe('custom-trigger', () => { @@ -151,10 +175,10 @@ describe('layout', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzLayoutModule, NzIconTestModule ], - declarations: [ NzDemoLayoutCustomTriggerComponent ], - providers : [], - schemas : [ NO_ERRORS_SCHEMA ] + imports: [NzLayoutModule, NzIconTestModule], + declarations: [NzDemoLayoutCustomTriggerComponent], + providers: [], + schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); @@ -187,16 +211,16 @@ describe('layout', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzLayoutModule ], - declarations: [ NzDemoLayoutResponsiveComponent ], - schemas : [ NO_ERRORS_SCHEMA ] - }).overrideComponent(NzSiderComponent, { - set: { - providers: [ - { provide: MediaMatcher, useClass: MatchMediaServiceSpy } - ] - } - }).compileComponents(); + imports: [NzLayoutModule], + declarations: [NzDemoLayoutResponsiveComponent], + schemas: [NO_ERRORS_SCHEMA] + }) + .overrideComponent(NzSiderComponent, { + set: { + providers: [{ provide: MediaMatcher, useClass: MatchMediaServiceSpy }] + } + }) + .compileComponents(); })); beforeEach(() => { @@ -211,8 +235,12 @@ describe('layout', () => { discardPeriodicTasks(); fixture.detectChanges(); console.log(sider.nativeElement.style.cssText); - expect(sider.nativeElement.style.cssText === 'flex: 0 0 0px; max-width: 0px; min-width: 0px; width: 0px;').toBe(true); - expect(sider.nativeElement.querySelector('.ant-layout-sider-zero-width-trigger').firstElementChild.getAttribute('type')).toBe('menu-fold'); + expect(sider.nativeElement.style.cssText === 'flex: 0 0 0px; max-width: 0px; min-width: 0px; width: 0px;').toBe( + true + ); + expect( + sider.nativeElement.querySelector('.ant-layout-sider-zero-width-trigger').firstElementChild.getAttribute('type') + ).toBe('menu-fold'); })); }); }); diff --git a/components/layout/nz-sider.component.ts b/components/layout/nz-sider.component.ts index 7701d5ca64a..7f4f06b88ba 100644 --- a/components/layout/nz-sider.component.ts +++ b/components/layout/nz-sider.component.ts @@ -28,30 +28,30 @@ import { NzLayoutComponent } from './nz-layout.component'; export type NzBreakPoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl'; @Component({ - selector : 'nz-sider', + selector: 'nz-sider', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-sider.component.html', - host : { + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-sider.component.html', + host: { '[class.ant-layout-sider-zero-width]': 'nzCollapsed && nzCollapsedWidth === 0', - '[class.ant-layout-sider-light]' : `nzTheme === 'light'`, - '[class.ant-layout-sider-collapsed]' : 'nzCollapsed', - '[style.flex]' : 'flexSetting', - '[style.max-width.px]' : 'widthSetting', - '[style.min-width.px]' : 'widthSetting', - '[style.width.px]' : 'widthSetting' + '[class.ant-layout-sider-light]': `nzTheme === 'light'`, + '[class.ant-layout-sider-collapsed]': 'nzCollapsed', + '[style.flex]': 'flexSetting', + '[style.max-width.px]': 'widthSetting', + '[style.min-width.px]': 'widthSetting', + '[style.width.px]': 'widthSetting' } }) export class NzSiderComponent implements OnInit, AfterViewInit, OnDestroy { private below = false; private destroy$ = new Subject(); private dimensionMap = { - xs : '480px', - sm : '576px', - md : '768px', - lg : '992px', - xl : '1200px', + xs: '480px', + sm: '576px', + md: '768px', + lg: '992px', + xl: '1200px', xxl: '1600px' }; @Input() nzWidth = 200; @@ -83,7 +83,7 @@ export class NzSiderComponent implements OnInit, AfterViewInit, OnDestroy { watchMatchMedia(): void { if (this.nzBreakpoint) { - const matchBelow = this.mediaMatcher.matchMedia(`(max-width: ${this.dimensionMap[ this.nzBreakpoint ]})`).matches; + const matchBelow = this.mediaMatcher.matchMedia(`(max-width: ${this.dimensionMap[this.nzBreakpoint]})`).matches; this.below = matchBelow; this.nzCollapsed = matchBelow; this.nzCollapsedChange.emit(matchBelow); @@ -99,14 +99,27 @@ export class NzSiderComponent implements OnInit, AfterViewInit, OnDestroy { } get isZeroTrigger(): boolean { - return this.nzCollapsible && this.nzTrigger && this.nzCollapsedWidth === 0 && ((this.nzBreakpoint && this.below) || (!this.nzBreakpoint)); + return ( + this.nzCollapsible && + this.nzTrigger && + this.nzCollapsedWidth === 0 && + ((this.nzBreakpoint && this.below) || !this.nzBreakpoint) + ); } get isSiderTrigger(): boolean { return this.nzCollapsible && this.nzTrigger && this.nzCollapsedWidth !== 0; } - constructor(@Optional() @Host() private nzLayoutComponent: NzLayoutComponent, private mediaMatcher: MediaMatcher, private ngZone: NgZone, private platform: Platform, private cdr: ChangeDetectorRef, renderer: Renderer2, elementRef: ElementRef) { + constructor( + @Optional() @Host() private nzLayoutComponent: NzLayoutComponent, + private mediaMatcher: MediaMatcher, + private ngZone: NgZone, + private platform: Platform, + private cdr: ChangeDetectorRef, + renderer: Renderer2, + elementRef: ElementRef + ) { renderer.addClass(elementRef.nativeElement, 'ant-layout-sider'); } @@ -121,8 +134,11 @@ export class NzSiderComponent implements OnInit, AfterViewInit, OnDestroy { Promise.resolve().then(() => this.watchMatchMedia()); this.ngZone.runOutsideAngular(() => { fromEvent(window, 'resize') - .pipe(auditTime(16), takeUntil(this.destroy$)) - .subscribe(() => this.watchMatchMedia()); + .pipe( + auditTime(16), + takeUntil(this.destroy$) + ) + .subscribe(() => this.watchMatchMedia()); }); } } @@ -134,5 +150,4 @@ export class NzSiderComponent implements OnInit, AfterViewInit, OnDestroy { this.nzLayoutComponent.destroySider(); } } - } diff --git a/components/list/demo/basic.ts b/components/list/demo/basic.ts index 049a711ff92..e3877ff0b31 100644 --- a/components/list/demo/basic.ts +++ b/components/list/demo/basic.ts @@ -3,21 +3,22 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-list-basic', template: ` -
    - - - - - - {{item.title}} - - - - - +
    + + + + + + {{ item.title }} + + + + + ` }) export class NzDemoListBasicComponent { diff --git a/components/list/demo/grid.ts b/components/list/demo/grid.ts index 7c0564b25e6..2d38fc09068 100644 --- a/components/list/demo/grid.ts +++ b/components/list/demo/grid.ts @@ -3,32 +3,32 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-list-grid', template: ` - - - - - - Card content - - - - - + + + + + + Card content + + + + + ` }) export class NzDemoListGridComponent { data = [ { - title: 'Title 1', + title: 'Title 1' }, { - title: 'Title 2', + title: 'Title 2' }, { - title: 'Title 3', + title: 'Title 3' }, { - title: 'Title 4', - }, + title: 'Title 4' + } ]; } diff --git a/components/list/demo/infinite-load.ts b/components/list/demo/infinite-load.ts index 42d68d2f8ff..9d4b682410d 100644 --- a/components/list/demo/infinite-load.ts +++ b/components/list/demo/infinite-load.ts @@ -5,20 +5,13 @@ import { ChangeDetectionStrategy, Component } from '@angular/core'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; @Component({ - selector : 'nz-demo-list-infinite-load', - template : ` + selector: 'nz-demo-list-infinite-load', + template: `
    - + - + - {{item.name.last}} + {{ item.name.last }} @@ -34,8 +27,8 @@ import { BehaviorSubject, Observable, Subscription } from 'rxjs';
    `, - styles : [ - ` + styles: [ + ` .demo-infinite-container { height: 300px; border: 1px solid #e8e8e8; @@ -52,8 +45,7 @@ import { BehaviorSubject, Observable, Subscription } from 'rxjs'; export class NzDemoListInfiniteLoadComponent { ds = new MyDataSource(this.http); - constructor(private http: HttpClient) { - } + constructor(private http: HttpClient) {} } class MyDataSource extends DataSource { @@ -96,18 +88,10 @@ class MyDataSource extends DataSource { this.fetchedPages.add(page); this.http - .get( - `https://randomuser.me/api/?results=${ - this.pageSize - }&inc=name,gender,email,nat&noinfo` - ) - .subscribe((res: any) => { - this.cachedData.splice( - page * this.pageSize, - this.pageSize, - ...res.results - ); - this.dataStream.next(this.cachedData); - }); + .get(`https://randomuser.me/api/?results=${this.pageSize}&inc=name,gender,email,nat&noinfo`) + .subscribe((res: any) => { + this.cachedData.splice(page * this.pageSize, this.pageSize, ...res.results); + this.dataStream.next(this.cachedData); + }); } } diff --git a/components/list/demo/loadmore.ts b/components/list/demo/loadmore.ts index 935b8b20869..52f1f27ab29 100644 --- a/components/list/demo/loadmore.ts +++ b/components/list/demo/loadmore.ts @@ -9,53 +9,60 @@ const fakeDataUrl = 'https://randomuser.me/api/?results=5&inc=name,gender,email, @Component({ selector: 'nz-demo-list-loadmore', template: ` - - - - - edit - more - - - {{item.name.last}} - - - - - - -
    - -
    -
    -
    + + + + + edit + more + + + {{ item.name.last }} + + + + + + +
    + +
    +
    +
    `, - styles: [ ` - .demo-loadmore-list { - min-height: 350px; - } - .loadmore { - text-align: center; - margin-top: 12px; - height: 32px; - line-height: 32px; - } - ` ] + styles: [ + ` + .demo-loadmore-list { + min-height: 350px; + } + .loadmore { + text-align: center; + margin-top: 12px; + height: 32px; + line-height: 32px; + } + ` + ] }) export class NzDemoListLoadmoreComponent implements OnInit { initLoading = true; // bug loadingMore = false; data: any[] = []; - list: Array<{ loading: boolean, name: any }> = []; + list: Array<{ loading: boolean; name: any }> = []; constructor(private http: HttpClient, private msg: NzMessageService) {} diff --git a/components/list/demo/resposive.ts b/components/list/demo/resposive.ts index 867d3043b7e..6415db232f2 100644 --- a/components/list/demo/resposive.ts +++ b/components/list/demo/resposive.ts @@ -3,20 +3,17 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-list-resposive', template: ` - - - - - - Card content - - - - - + + + + + + Card content + + + + + ` }) export class NzDemoListResposiveComponent { diff --git a/components/list/demo/simple.ts b/components/list/demo/simple.ts index cdc05e7fb2c..19d7f3bdaf9 100644 --- a/components/list/demo/simple.ts +++ b/components/list/demo/simple.ts @@ -3,24 +3,32 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-list-simple', template: ` -

    Default Size

    - - - -

    Small Size

    - - - -

    Large Size

    - - - +

    Default Size

    + + + +

    Small Size

    + + + +

    Large Size

    + + + ` }) export class NzDemoListSimpleComponent { diff --git a/components/list/demo/vertical.ts b/components/list/demo/vertical.ts index 75bf6366582..6bc8f43d708 100644 --- a/components/list/demo/vertical.ts +++ b/components/list/demo/vertical.ts @@ -3,35 +3,35 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-list-vertical', template: ` - - - - 156 - 156 - 2 - - {{item.title}} - - - logo - - - - -
    ant design footer part
    -
    - - - -
    + + + + 156 + 156 + 2 + + {{ item.title }} + + + logo + + + + +
    ant design footer part
    +
    + + + +
    ` }) export class NzDemoListVerticalComponent implements OnInit { @@ -49,8 +49,9 @@ export class NzDemoListVerticalComponent implements OnInit { title: `ant design part ${index} (page: ${pi})`, avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.', - content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' + content: + 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' }; }); } -} \ No newline at end of file +} diff --git a/components/list/interface.ts b/components/list/interface.ts index 2b33a970099..c8cfab0de4c 100644 --- a/components/list/interface.ts +++ b/components/list/interface.ts @@ -3,13 +3,13 @@ export type ColumnCount = 1 | 2 | 3 | 4 | 6 | 8 | 12 | 24; export type ColumnType = 'gutter' | 'column' | 'xs' | 'sm' | 'md' | 'lg' | 'xl'; export interface NzListGrid { - gutter?: number; - span?: number; - column?: ColumnCount; - xs?: ColumnCount; - sm?: ColumnCount; - md?: ColumnCount; - lg?: ColumnCount; - xl?: ColumnCount; - xxl?: ColumnCount; + gutter?: number; + span?: number; + column?: ColumnCount; + xs?: ColumnCount; + sm?: ColumnCount; + md?: ColumnCount; + lg?: ColumnCount; + xl?: ColumnCount; + xxl?: ColumnCount; } diff --git a/components/list/list.spec.ts b/components/list/list.spec.ts index d4d5781fc33..773d686a6a5 100644 --- a/components/list/list.spec.ts +++ b/components/list/list.spec.ts @@ -13,8 +13,8 @@ describe('list', () => { let dl: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ - imports: [ NzListModule, NzIconTestModule ], - declarations: [ TestListComponent, TestListWithTemplateComponent, TestListItemComponent ] + imports: [NzListModule, NzIconTestModule], + declarations: [TestListComponent, TestListWithTemplateComponent, TestListItemComponent] }).compileComponents(); fixture = TestBed.createComponent(TestListComponent); context = fixture.componentInstance; @@ -23,9 +23,8 @@ describe('list', () => { }); describe('[fields]', () => { - describe('#nzItemLayout', () => { - for (const item of [ { type: 'default', ret: false }, { type: 'vertical', ret: true } ]) { + for (const item of [{ type: 'default', ret: false }, { type: 'vertical', ret: true }]) { it(`[${item.type}]`, () => { context.nzItemLayout = item.type; fixture.detectChanges(); @@ -35,7 +34,7 @@ describe('list', () => { }); describe('#nzBordered', () => { - for (const value of [ true, false ]) { + for (const value of [true, false]) { it(`[${value}]`, () => { context.nzBordered = value; fixture.detectChanges(); @@ -63,13 +62,15 @@ describe('list', () => { const fixtureTemp = TestBed.createComponent(TestListWithTemplateComponent); fixtureTemp.detectChanges(); const footerEl = fixtureTemp.debugElement.query(By.css('.ant-list-footer')); - expect((footerEl.nativeElement as HTMLDivElement).innerText).toBe(fixtureTemp.componentInstance.footer as string); + expect((footerEl.nativeElement as HTMLDivElement).innerText).toBe(fixtureTemp.componentInstance + .footer as string); }); it('change string to template', () => { const fixtureTemp = TestBed.createComponent(TestListWithTemplateComponent); fixtureTemp.detectChanges(); const footerEl = fixtureTemp.debugElement.query(By.css('.ant-list-footer')); - expect((footerEl.nativeElement as HTMLDivElement).innerText).toBe(fixtureTemp.componentInstance.footer as string); + expect((footerEl.nativeElement as HTMLDivElement).innerText).toBe(fixtureTemp.componentInstance + .footer as string); (fixtureTemp.debugElement.query(By.css('#change')).nativeElement as HTMLButtonElement).click(); fixtureTemp.detectChanges(); expect(fixtureTemp.debugElement.query(By.css('.list-footer')) != null).toBe(true); @@ -91,7 +92,7 @@ describe('list', () => { }); describe('#nzSplit', () => { - for (const value of [ true, false ]) { + for (const value of [true, false]) { it(`[${value}]`, () => { context.nzSplit = value; fixture.detectChanges(); @@ -101,7 +102,7 @@ describe('list', () => { }); describe('#nzLoading', () => { - for (const value of [ true, false ]) { + for (const value of [true, false]) { it(`[${value}]`, () => { context.nzLoading = value; fixture.detectChanges(); @@ -162,7 +163,9 @@ describe('list', () => { expect(fixtureTemp.debugElement.query(By.css('#item-string .ant-list-item-extra')) != null).toBe(true); }); it('with custom template of [nzContent]', () => { - expect(fixtureTemp.debugElement.query(By.css('#item-template .ant-list-item-content .item-content')) != null).toBe(true); + expect( + fixtureTemp.debugElement.query(By.css('#item-template .ant-list-item-content .item-content')) != null + ).toBe(true); }); }); @@ -183,40 +186,42 @@ describe('list', () => { expect(fixtureTemp.debugElement.query(By.css('#item-template .item-avatar')) != null).toBe(true); }); }); - }); @Component({ template: ` - - - - - - - - -
    loadmore
    -
    - - - -
    + + + + + + + + +
    loadmore
    +
    + + + +
    ` }) class TestListComponent { @@ -235,57 +240,50 @@ class TestListComponent { 'Japanese princess to wed commoner.' ]; // tslint:disable-next-line:no-any - nzGrid: any = {gutter: 16, span: 12}; + nzGrid: any = { gutter: 16, span: 12 }; } @Component({ template: ` - - - -

    header

    -
    + + + +

    header

    +
    ` }) class TestListWithTemplateComponent { - @ViewChild('nzFooter') nzFooter: TemplateRef; footer: string | TemplateRef = 'footer with string'; - } @Component({ template: ` - - - 156 - - logo - - - - - - - -

    nzContent

    - -

    nzTitle

    -

    nzAvatar

    -

    nzDescription

    -
    -
    -
    + + + 156 + + logo + + + + + + + +

    nzContent

    + +

    nzTitle

    +

    nzAvatar

    +

    nzDescription

    +
    +
    +
    ` }) -class TestListItemComponent { -} +class TestListItemComponent {} diff --git a/components/list/nz-list-item-meta.component.ts b/components/list/nz-list-item-meta.component.ts index 73d94cbe90e..e1c50ee6b90 100644 --- a/components/list/nz-list-item-meta.component.ts +++ b/components/list/nz-list-item-meta.component.ts @@ -9,14 +9,13 @@ import { } from '@angular/core'; @Component({ - selector : 'nz-list-item-meta', - templateUrl : './nz-list-item-meta.component.html', + selector: 'nz-list-item-meta', + templateUrl: './nz-list-item-meta.component.html', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None }) export class NzListItemMetaComponent { - avatarStr = ''; avatarTpl: TemplateRef; diff --git a/components/list/nz-list-item.component.ts b/components/list/nz-list-item.component.ts index 06e5b3eeb24..82eef345bd9 100644 --- a/components/list/nz-list-item.component.ts +++ b/components/list/nz-list-item.component.ts @@ -4,7 +4,8 @@ import { ContentChildren, ElementRef, Input, - QueryList, Renderer2, + QueryList, + Renderer2, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -12,14 +13,14 @@ import { import { NzListItemMetaComponent } from './nz-list-item-meta.component'; @Component({ - selector : 'nz-list-item', - templateUrl : './nz-list-item.component.html', + selector: 'nz-list-item', + templateUrl: './nz-list-item.component.html', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzListItemComponent { - @ContentChildren(NzListItemMetaComponent) metas !: QueryList; + @ContentChildren(NzListItemMetaComponent) metas!: QueryList; @Input() nzActions: Array> = []; @Input() nzContent: string | TemplateRef; @Input() nzExtra: TemplateRef; diff --git a/components/list/nz-list.component.ts b/components/list/nz-list.component.ts index dde78e89875..848cb41dc48 100644 --- a/components/list/nz-list.component.ts +++ b/components/list/nz-list.component.ts @@ -16,20 +16,22 @@ import { InputBoolean } from '../core/util/convert'; import { NzListGrid } from './interface'; @Component({ - selector : 'nz-list', - templateUrl : './nz-list.component.html', - providers : [ NzUpdateHostClassService ], + selector: 'nz-list', + templateUrl: './nz-list.component.html', + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - styles : [ ` - nz-list, nz-list nz-spin { - display: block; - } - ` ] + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + styles: [ + ` + nz-list, + nz-list nz-spin { + display: block; + } + ` + ] }) export class NzListComponent implements OnInit, OnChanges { - // #region fields // tslint:disable-next-line:no-any @Input() nzDataSource: any[]; @@ -66,23 +68,22 @@ export class NzListComponent implements OnInit, OnChanges { private _setClassMap(): void { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-vertical` ] : this.nzItemLayout === 'vertical', - [ `${this.prefixCls}-lg` ] : this.nzSize === 'large', - [ `${this.prefixCls}-sm` ] : this.nzSize === 'small', - [ `${this.prefixCls}-split` ] : this.nzSplit, - [ `${this.prefixCls}-bordered` ] : this.nzBordered, - [ `${this.prefixCls}-loading` ] : this.nzLoading, - [ `${this.prefixCls}-grid` ] : this.nzGrid, - [ `${this.prefixCls}-something-after-last-item` ]: !!(this.nzLoadMore || this.nzPagination || this.nzFooter) + [this.prefixCls]: true, + [`${this.prefixCls}-vertical`]: this.nzItemLayout === 'vertical', + [`${this.prefixCls}-lg`]: this.nzSize === 'large', + [`${this.prefixCls}-sm`]: this.nzSize === 'small', + [`${this.prefixCls}-split`]: this.nzSplit, + [`${this.prefixCls}-bordered`]: this.nzBordered, + [`${this.prefixCls}-loading`]: this.nzLoading, + [`${this.prefixCls}-grid`]: this.nzGrid, + [`${this.prefixCls}-something-after-last-item`]: !!(this.nzLoadMore || this.nzPagination || this.nzFooter) }; this.updateHostClassService.updateHostClass(this.el.nativeElement, classMap); } // #endregion - constructor(private el: ElementRef, private updateHostClassService: NzUpdateHostClassService) { - } + constructor(private el: ElementRef, private updateHostClassService: NzUpdateHostClassService) {} ngOnInit(): void { this._setClassMap(); diff --git a/components/list/nz-list.module.ts b/components/list/nz-list.module.ts index 59e43a14c87..d81584191b1 100644 --- a/components/list/nz-list.module.ts +++ b/components/list/nz-list.module.ts @@ -12,24 +12,8 @@ import { NzListItemComponent } from './nz-list-item.component'; import { NzListComponent } from './nz-list.component'; @NgModule({ - imports : [ - CommonModule, - NzSpinModule, - NzGridModule, - NzAvatarModule, - NzAddOnModule, - NzEmptyModule - ], - declarations: [ - NzListComponent, - NzListItemComponent, - NzListItemMetaComponent - ], - exports : [ - NzListComponent, - NzListItemComponent, - NzListItemMetaComponent - ] + imports: [CommonModule, NzSpinModule, NzGridModule, NzAvatarModule, NzAddOnModule, NzEmptyModule], + declarations: [NzListComponent, NzListItemComponent, NzListItemMetaComponent], + exports: [NzListComponent, NzListItemComponent, NzListItemMetaComponent] }) -export class NzListModule { -} +export class NzListModule {} diff --git a/components/mention/demo/async.ts b/components/mention/demo/async.ts index 1e7ac527fd0..147f65d49f0 100755 --- a/components/mention/demo/async.ts +++ b/components/mention/demo/async.ts @@ -2,29 +2,23 @@ import { Component, ViewEncapsulation } from '@angular/core'; import { MentionOnSearchTypes } from 'ng-zorro-antd'; @Component({ - selector : 'nz-demo-mention-async', + selector: 'nz-demo-mention-async', encapsulation: ViewEncapsulation.None, - template : ` - - - -` + template: ` + + + + ` }) export class NzDemoMentionAsyncComponent { inputValue: string; loading = false; suggestions: string[] = []; - onSearchChange({value}: MentionOnSearchTypes): void { + onSearchChange({ value }: MentionOnSearchTypes): void { console.log(`search: ${value}`); this.loading = true; - this.fetchSuggestions(value, (suggestions) => { + this.fetchSuggestions(value, suggestions => { console.log(suggestions); this.suggestions = suggestions; this.loading = false; diff --git a/components/mention/demo/avatar.ts b/components/mention/demo/avatar.ts index 1bbea5f298e..bd325eb5da5 100755 --- a/components/mention/demo/avatar.ts +++ b/components/mention/demo/avatar.ts @@ -1,31 +1,27 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-avatar', + selector: 'nz-demo-mention-avatar', encapsulation: ViewEncapsulation.None, - template : ` - - + template: ` + + {{ framework.name }} - {{ framework.type }} `, - styles : [ ` - .ant-avatar.ant-avatar-sm { - width: 14px; - height: 14px; - margin-right: 8px; - position: relative - } - ` ] + styles: [ + ` + .ant-avatar.ant-avatar-sm { + width: 14px; + height: 14px; + margin-right: 8px; + position: relative; + } + ` + ] }) export class NzDemoMentionAvatarComponent { inputValue: string; @@ -33,10 +29,10 @@ export class NzDemoMentionAvatarComponent { { name: 'React', type: 'JavaScript', icon: 'https://zos.alipayobjects.com/rmsportal/LFIeMPzdLcLnEUe.svg' }, { name: 'Angular', type: 'JavaScript', icon: 'https://zos.alipayobjects.com/rmsportal/PJTbxSvzYWjDZnJ.png' }, { name: 'Dva', type: 'Javascript', icon: 'https://zos.alipayobjects.com/rmsportal/EYPwSeEJKxDtVxI.png' }, - { name: 'Flask', type: 'Python', icon: 'https://zos.alipayobjects.com/rmsportal/xaypBUijfnpAlXE.png' }, + { name: 'Flask', type: 'Python', icon: 'https://zos.alipayobjects.com/rmsportal/xaypBUijfnpAlXE.png' } ]; - valueWith = (data: { name: string, type: string, icon: string }) => data.name; + valueWith = (data: { name: string; type: string; icon: string }) => data.name; onSelect(value: string): void { console.log(value); diff --git a/components/mention/demo/basic.ts b/components/mention/demo/basic.ts index 3651cf066ce..f3d3d839790 100644 --- a/components/mention/demo/basic.ts +++ b/components/mention/demo/basic.ts @@ -1,21 +1,19 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-basic', + selector: 'nz-demo-mention-basic', encapsulation: ViewEncapsulation.None, - template : ` - - - -` + template: ` + + + + ` }) export class NzDemoMentionBasicComponent { inputValue: string = '@afc163'; diff --git a/components/mention/demo/controlled.ts b/components/mention/demo/controlled.ts index 4d2213849f4..dfa06be9302 100644 --- a/components/mention/demo/controlled.ts +++ b/components/mention/demo/controlled.ts @@ -1,60 +1,46 @@ import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; -import { - AbstractControl, - FormBuilder, - FormControl, - FormGroup, - Validators -} from '@angular/forms'; +import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ - selector : 'nz-demo-mention-controlled', + selector: 'nz-demo-mention-controlled', encapsulation: ViewEncapsulation.None, - template : ` -
    - - Top coders - - - - - - More than one must be selected! - - - - - - -     - - - -
    -` + template: ` +
    + + Top coders + + + + + + More than one must be selected! + + + + + + +     + + + +
    + ` }) export class NzDemoMentionControlledComponent implements OnInit { - suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご']; validateForm: FormGroup; @ViewChild('mentions') mentionChild: any; - get mention(): AbstractControl { return this.validateForm.get('mention')!; } - - constructor(private fb: FormBuilder) { - + get mention(): AbstractControl { + return this.validateForm.get('mention')!; } + constructor(private fb: FormBuilder) {} + ngOnInit(): void { this.validateForm = this.fb.group({ - mention: [ '@afc163 ', [ Validators.required, this.mentionValidator ] ] + mention: ['@afc163 ', [Validators.required, this.mentionValidator]] }); } @@ -65,7 +51,7 @@ export class NzDemoMentionControlledComponent implements OnInit { return { confirm: true, error: true }; } return {}; - } + }; submitForm(): void { this.mention.markAsDirty(); @@ -82,5 +68,4 @@ export class NzDemoMentionControlledComponent implements OnInit { mention: '@afc163 ' }); } - } diff --git a/components/mention/demo/custom-tag.ts b/components/mention/demo/custom-tag.ts index e31addfaf68..d33254f0094 100644 --- a/components/mention/demo/custom-tag.ts +++ b/components/mention/demo/custom-tag.ts @@ -1,24 +1,16 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-custom-tag', + selector: 'nz-demo-mention-custom-tag', encapsulation: ViewEncapsulation.None, - template : ` - - - + template: ` + + + {{ framework.name }} - {{ framework.type }} - - -` + + + ` }) export class NzDemoMentionCustomTagComponent { inputValue: string; @@ -30,7 +22,7 @@ export class NzDemoMentionCustomTagComponent { { name: 'Django', type: 'Python' } ]; - valueWith = (data: { name: string, type: string }) => data.name; + valueWith = (data: { name: string; type: string }) => data.name; onSelect(value: string): void { console.log(value); diff --git a/components/mention/demo/multilines.ts b/components/mention/demo/multilines.ts index 6bbd4a5981f..e63088bb271 100644 --- a/components/mention/demo/multilines.ts +++ b/components/mention/demo/multilines.ts @@ -1,22 +1,16 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-multilines', + selector: 'nz-demo-mention-multilines', encapsulation: ViewEncapsulation.None, - template : ` - - - -` +
    + ` }) export class NzDemoMentionMultilinesComponent { inputValue: string; suggestions = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご']; - } diff --git a/components/mention/demo/multiple-trigger.ts b/components/mention/demo/multiple-trigger.ts index 6d069572fa9..fd3154f171c 100755 --- a/components/mention/demo/multiple-trigger.ts +++ b/components/mention/demo/multiple-trigger.ts @@ -2,20 +2,18 @@ import { Component, ViewEncapsulation } from '@angular/core'; import { MentionOnSearchTypes } from 'ng-zorro-antd'; @Component({ - selector : 'nz-demo-mention-multiple-trigger', + selector: 'nz-demo-mention-multiple-trigger', encapsulation: ViewEncapsulation.None, - template : ` - - - -` + template: ` + + + + ` }) export class NzDemoMentionMultipleTriggerComponent { inputValue: string; @@ -23,9 +21,8 @@ export class NzDemoMentionMultipleTriggerComponent { users = ['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご']; tags = ['1.0', '2.0', '3.0']; - onSearchChange({value, prefix}: MentionOnSearchTypes): void { + onSearchChange({ value, prefix }: MentionOnSearchTypes): void { console.log('nzOnSearchChange', value, prefix); this.suggestions = prefix === '@' ? this.users : this.tags; } - } diff --git a/components/mention/demo/placement.ts b/components/mention/demo/placement.ts index ae1bc51b622..ae72ff3d3d2 100755 --- a/components/mention/demo/placement.ts +++ b/components/mention/demo/placement.ts @@ -1,20 +1,13 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-placement', + selector: 'nz-demo-mention-placement', encapsulation: ViewEncapsulation.None, - template : ` - - - -` + template: ` + + + + ` }) export class NzDemoMentionPlacementComponent { inputValue: string; diff --git a/components/mention/demo/preview.ts b/components/mention/demo/preview.ts index 6c89438df0c..03ec24e21ae 100644 --- a/components/mention/demo/preview.ts +++ b/components/mention/demo/preview.ts @@ -1,27 +1,27 @@ import { Component, ViewEncapsulation } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ - selector : 'nz-demo-mention-preview', + selector: 'nz-demo-mention-preview', encapsulation: ViewEncapsulation.None, - template : ` - + template: ` + - - + + -
    
    +        
    
           
    -` + ` }) export class NzDemoMentionPreviewComponent { inputValue: string = 'Switch tab view preview @NG-ZORRO '; @@ -46,8 +46,10 @@ export class NzDemoMentionPreviewComponent { renderPreView(): void { if (this.inputValue) { const regex = this.getRegExp('@'); - const previewValue = this.inputValue - .replace(regex, match => `${match}`); + const previewValue = this.inputValue.replace( + regex, + match => `${match}` + ); this.preview = this.sanitizer.bypassSecurityTrustHtml(previewValue); } } diff --git a/components/mention/demo/readonly.ts b/components/mention/demo/readonly.ts index 79bb6045c79..4bbc9858863 100755 --- a/components/mention/demo/readonly.ts +++ b/components/mention/demo/readonly.ts @@ -1,26 +1,21 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-mention-readonly', + selector: 'nz-demo-mention-readonly', encapsulation: ViewEncapsulation.None, - template : ` - - - - -` + template: ` + + + + + ` }) export class NzDemoMentionReadonlyComponent { inputValue: string; diff --git a/components/mention/nz-mention-suggestions.ts b/components/mention/nz-mention-suggestions.ts index 718ba451298..9b9426f7f42 100644 --- a/components/mention/nz-mention-suggestions.ts +++ b/components/mention/nz-mention-suggestions.ts @@ -3,4 +3,4 @@ import { Directive } from '@angular/core'; @Directive({ selector: '[nzMentionSuggestion]' }) -export class NzMentionSuggestionDirective { } +export class NzMentionSuggestionDirective {} diff --git a/components/mention/nz-mention-trigger.ts b/components/mention/nz-mention-trigger.ts index dc6ae54ff76..aed013a1723 100644 --- a/components/mention/nz-mention-trigger.ts +++ b/components/mention/nz-mention-trigger.ts @@ -13,17 +13,15 @@ export const NZ_MENTION_TRIGGER_ACCESSOR: ExistingProvider = { selector: 'input[nzMentionTrigger], textarea[nzMentionTrigger]', providers: [NZ_MENTION_TRIGGER_ACCESSOR], host: { - 'autocomplete': 'off', - '(focusin)' : 'onFocusin.emit()', - '(blur)' : 'onBlur.emit()', - '(input)' : 'onInput.emit($event)', - '(keydown)' : 'onKeydown.emit($event)', - '(click)' : 'onClick.emit($event)' + autocomplete: 'off', + '(focusin)': 'onFocusin.emit()', + '(blur)': 'onBlur.emit()', + '(input)': 'onInput.emit($event)', + '(keydown)': 'onKeydown.emit($event)', + '(click)': 'onClick.emit($event)' } }) - export class NzMentionTriggerDirective implements ControlValueAccessor, OnDestroy { - onChange: (value: string) => void; onTouched: () => void; @@ -34,8 +32,7 @@ export class NzMentionTriggerDirective implements ControlValueAccessor, OnDestro readonly onClick: EventEmitter = new EventEmitter(); value: string; - constructor(public el: ElementRef) { - } + constructor(public el: ElementRef) {} ngOnDestroy(): void { this.completeEvents(); @@ -84,5 +81,4 @@ export class NzMentionTriggerDirective implements ControlValueAccessor, OnDestro registerOnTouched(fn: () => void): void { this.onTouched = fn; } - } diff --git a/components/mention/nz-mention.component.ts b/components/mention/nz-mention.component.ts index b9c5eb8c308..c08294bdb09 100644 --- a/components/mention/nz-mention.component.ts +++ b/components/mention/nz-mention.component.ts @@ -12,7 +12,8 @@ import { TemplatePortal } from '@angular/cdk/portal'; import { DOCUMENT } from '@angular/common'; import { AfterContentInit, - ChangeDetectionStrategy, ChangeDetectorRef, + ChangeDetectionStrategy, + ChangeDetectorRef, Component, ContentChild, EventEmitter, @@ -51,24 +52,24 @@ export interface Mention { export type MentionPlacement = 'top' | 'bottom'; @Component({ - selector : 'nz-mention', - templateUrl : './nz-mention.component.html', + selector: 'nz-mention', + templateUrl: './nz-mention.component.html', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - styles : [ ` - .ant-mention-dropdown { - top: 100%; - left: 0; - position: relative; - width: 100%; - margin-top: 4px; - margin-bottom: 4px; - } - ` ] + changeDetection: ChangeDetectionStrategy.OnPush, + styles: [ + ` + .ant-mention-dropdown { + top: 100%; + left: 0; + position: relative; + width: 100%; + margin-top: 4px; + margin-bottom: 4px; + } + ` + ] }) - export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChanges { - @Input() nzValueWith: (value: any) => string = value => value; // tslint:disable-line:no-any @Input() nzPrefix: string | string[] = '@'; @Input() @InputBoolean() nzLoading = false; @@ -107,11 +108,12 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange return this.trigger.el.nativeElement; } - constructor(@Optional() @Inject(DOCUMENT) private ngDocument: any, // tslint:disable-line:no-any - private changeDetectorRef: ChangeDetectorRef, - private overlay: Overlay, - private viewContainerRef: ViewContainerRef) { - } + constructor( + @Optional() @Inject(DOCUMENT) private ngDocument: any, // tslint:disable-line:no-any + private changeDetectorRef: ChangeDetectorRef, + private overlay: Overlay, + private viewContainerRef: ViewContainerRef + ) {} ngOnChanges(changes: SimpleChanges): void { if (changes.hasOwnProperty('nzSuggestions')) { @@ -153,9 +155,9 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange selectSuggestion(suggestion: string | {}): void { const value = this.nzValueWith(suggestion); this.trigger.insertMention({ - mention : value, + mention: value, startPos: this.cursorMentionStart, - endPos : this.cursorMentionEnd + endPos: this.cursorMentionEnd }); this.nzOnSelect.emit(suggestion); this.closeDropdown(); @@ -172,25 +174,24 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange private handleKeydown(event: KeyboardEvent): void { const keyCode = event.keyCode; if (this.isOpen && keyCode === ENTER && this.activeIndex !== -1 && this.filteredSuggestions.length) { - this.selectSuggestion(this.filteredSuggestions[ this.activeIndex ]); + this.selectSuggestion(this.filteredSuggestions[this.activeIndex]); event.preventDefault(); } else if (keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW) { this.resetDropdown(); event.stopPropagation(); } else { - if (this.isOpen && (keyCode === TAB || keyCode === ESCAPE)) { this.closeDropdown(); return; } - if (this.isOpen && (keyCode === UP_ARROW)) { + if (this.isOpen && keyCode === UP_ARROW) { this.setPreviousItemActive(); event.preventDefault(); event.stopPropagation(); } - if (this.isOpen && (keyCode === DOWN_ARROW)) { + if (this.isOpen && keyCode === DOWN_ARROW) { this.setNextItemActive(); event.preventDefault(); event.stopPropagation(); @@ -216,13 +217,16 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange this.previousValue = value; if (emit) { this.nzOnSearchChange.emit({ - value : this.cursorMention!.substring(1), - prefix: this.cursorMention![ 0 ] + value: this.cursorMention!.substring(1), + prefix: this.cursorMention![0] }); } const searchValue = suggestions.toLowerCase(); - this.filteredSuggestions = this.nzSuggestions - .filter(suggestion => this.nzValueWith(suggestion).toLowerCase().includes(searchValue)); + this.filteredSuggestions = this.nzSuggestions.filter(suggestion => + this.nzValueWith(suggestion) + .toLowerCase() + .includes(searchValue) + ); } private resetDropdown(emit: boolean = true): void { @@ -238,16 +242,12 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange } private setNextItemActive(): void { - this.activeIndex = this.activeIndex + 1 <= this.filteredSuggestions.length - 1 - ? this.activeIndex + 1 - : 0; + this.activeIndex = this.activeIndex + 1 <= this.filteredSuggestions.length - 1 ? this.activeIndex + 1 : 0; this.changeDetectorRef.markForCheck(); } private setPreviousItemActive(): void { - this.activeIndex = this.activeIndex - 1 < 0 - ? this.filteredSuggestions.length - 1 - : this.activeIndex - 1; + this.activeIndex = this.activeIndex - 1 < 0 ? this.filteredSuggestions.length - 1 : this.activeIndex - 1; this.changeDetectorRef.markForCheck(); } @@ -259,16 +259,18 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange private resetCursorMention(): void { const value = this.triggerNativeElement.value.replace(/[\r\n]/g, ' ') || ''; const selectionStart = this.triggerNativeElement.selectionStart!; - const prefix = typeof this.nzPrefix === 'string' ? [ this.nzPrefix ] : this.nzPrefix; + const prefix = typeof this.nzPrefix === 'string' ? [this.nzPrefix] : this.nzPrefix; let i = prefix.length; while (i >= 0) { - const startPos = value.lastIndexOf(prefix[ i ], selectionStart); + const startPos = value.lastIndexOf(prefix[i], selectionStart); const endPos = value.indexOf(' ', selectionStart) > -1 ? value.indexOf(' ', selectionStart) : value.length; const mention = value.substring(startPos, endPos); - if ((startPos > 0 && value[ startPos - 1 ] !== ' ') - || startPos < 0 - || mention.includes(prefix[ i ], 1) - || mention.includes(' ')) { + if ( + (startPos > 0 && value[startPos - 1] !== ' ') || + startPos < 0 || + mention.includes(prefix[i], 1) || + mention.includes(' ') + ) { this.cursorMention = null; this.cursorMentionStart = -1; this.cursorMentionEnd = -1; @@ -284,17 +286,18 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange private updatePositions(): void { const coordinates = getCaretCoordinates(this.triggerNativeElement, this.cursorMentionStart); - const top = coordinates.top - - this.triggerNativeElement.getBoundingClientRect().height - - this.triggerNativeElement.scrollTop - + (this.nzPlacement === 'bottom' ? coordinates.height : 0); + const top = + coordinates.top - + this.triggerNativeElement.getBoundingClientRect().height - + this.triggerNativeElement.scrollTop + + (this.nzPlacement === 'bottom' ? coordinates.height : 0); const left = coordinates.left - this.triggerNativeElement.scrollLeft; this.positionStrategy.withDefaultOffsetX(left).withDefaultOffsetY(top); if (this.nzPlacement === 'bottom') { - this.positionStrategy.withPositions([ DEFAULT_MENTION_POSITIONS[ 0 ] ]); + this.positionStrategy.withPositions([DEFAULT_MENTION_POSITIONS[0]]); } if (this.nzPlacement === 'top') { - this.positionStrategy.withPositions([ DEFAULT_MENTION_POSITIONS[ 1 ] ]); + this.positionStrategy.withPositions([DEFAULT_MENTION_POSITIONS[1]]); } this.positionStrategy.apply(); } @@ -303,8 +306,7 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange return merge( fromEvent(this.ngDocument, 'click'), fromEvent(this.ngDocument, 'touchend') - ) - .subscribe((event: MouseEvent | TouchEvent) => { + ).subscribe((event: MouseEvent | TouchEvent) => { const clickTarget = event.target as HTMLElement; if (clickTarget !== this.trigger.el.nativeElement && this.isOpen) { this.closeDropdown(); @@ -327,7 +329,7 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange private getOverlayConfig(): OverlayConfig { return new OverlayConfig({ positionStrategy: this.getOverlayPosition(), - scrollStrategy : this.overlay.scrollStrategies.reposition() + scrollStrategy: this.overlay.scrollStrategies.reposition() }); } @@ -336,12 +338,12 @@ export class NzMentionComponent implements OnDestroy, AfterContentInit, OnChange new ConnectionPositionPair({ originX: 'start', originY: 'bottom' }, { overlayX: 'start', overlayY: 'top' }), new ConnectionPositionPair({ originX: 'start', originY: 'top' }, { overlayX: 'start', overlayY: 'bottom' }) ]; - this.positionStrategy = this.overlay.position() - .flexibleConnectedTo(this.trigger.el) - .withPositions(positions) - .withFlexibleDimensions(false) - .withPush(false); + this.positionStrategy = this.overlay + .position() + .flexibleConnectedTo(this.trigger.el) + .withPositions(positions) + .withFlexibleDimensions(false) + .withPush(false); return this.positionStrategy; } - } diff --git a/components/mention/nz-mention.module.ts b/components/mention/nz-mention.module.ts index dee811ee39f..aee52e501f2 100644 --- a/components/mention/nz-mention.module.ts +++ b/components/mention/nz-mention.module.ts @@ -10,9 +10,8 @@ import { NzMentionComponent } from './nz-mention.component'; const COMPONENTS = [NzMentionComponent, NzMentionTriggerDirective, NzMentionSuggestionDirective]; @NgModule({ - imports : [ CommonModule, FormsModule, OverlayModule, NzIconModule ], - declarations: [ ...COMPONENTS ], - exports : [ ...COMPONENTS ] + imports: [CommonModule, FormsModule, OverlayModule, NzIconModule], + declarations: [...COMPONENTS], + exports: [...COMPONENTS] }) -export class NzMentionModule { -} +export class NzMentionModule {} diff --git a/components/mention/nz-mention.spec.ts b/components/mention/nz-mention.spec.ts index 96fee96d6e0..53c20922322 100644 --- a/components/mention/nz-mention.spec.ts +++ b/components/mention/nz-mention.spec.ts @@ -2,11 +2,7 @@ import { Directionality } from '@angular/cdk/bidi'; import { DOWN_ARROW, ENTER, ESCAPE, RIGHT_ARROW, TAB, UP_ARROW } from '@angular/cdk/keycodes'; import { OverlayContainer } from '@angular/cdk/overlay'; import { ScrollDispatcher } from '@angular/cdk/scrolling'; -import { - Component, - NgZone, - ViewChild -} from '@angular/core'; +import { Component, NgZone, ViewChild } from '@angular/core'; import { async, fakeAsync, flush, inject, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; @@ -36,29 +32,36 @@ describe('mention', () => { beforeEach(async(() => { const dir = 'ltr'; TestBed.configureTestingModule({ - imports : [ NzMentionModule, NzInputModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ - NzTestSimpleMentionComponent, - NzTestPropertyMentionComponent + imports: [ + NzMentionModule, + NzInputModule, + NoopAnimationsModule, + FormsModule, + ReactiveFormsModule, + NzIconTestModule ], - providers : [ + declarations: [NzTestSimpleMentionComponent, NzTestPropertyMentionComponent], + providers: [ { provide: Directionality, useFactory: () => ({ value: dir }) }, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject }) }, - {provide: NgZone, useFactory: () => { + { + provide: NgZone, + useFactory: () => { zone = new MockNgZone(); return zone; - }} + } + } ] }); TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -120,11 +123,9 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); flush(); - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); dispatchFakeEvent(document, 'click'); - expect(mention.isOpen) - .toBe(false); + expect(mention.isOpen).toBe(false); })); it('should close the dropdown when the user taps away on a touch device', fakeAsync(() => { @@ -133,8 +134,7 @@ describe('mention', () => { fixture.detectChanges(); flush(); dispatchFakeEvent(document, 'touchend'); - expect(mention.isOpen) - .toBe(false); + expect(mention.isOpen).toBe(false); })); it('should close the dropdown when an option is clicked', fakeAsync(() => { @@ -150,14 +150,10 @@ describe('mention', () => { fixture.detectChanges(); tick(500); - expect(mention.isOpen) - .toBe(false); - expect(overlayContainerElement.textContent) - .toEqual(''); - expect(textarea.value) - .toEqual('@angular '); + expect(mention.isOpen).toBe(false); + expect(overlayContainerElement.textContent).toEqual(''); + expect(textarea.value).toEqual('@angular '); })); - }); describe('keyboard events', () => { @@ -191,11 +187,11 @@ describe('mention', () => { fixture.detectChanges(); const mention = fixture.componentInstance.mention; - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); fixture.componentInstance.trigger.onKeydown.emit(DOWN_ARROW_EVENT); fixture.detectChanges(); @@ -209,11 +205,11 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); const mention = fixture.componentInstance.mention; - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); [1, 2, 3, 4, 5].forEach(() => fixture.componentInstance.trigger.onKeydown.emit(DOWN_ARROW_EVENT)); fixture.detectChanges(); @@ -221,7 +217,6 @@ describe('mention', () => { expect(optionEls[1].classList).not.toContain('focus'); expect(optionEls[4].classList).not.toContain('focus'); expect(optionEls[0].classList).toContain('focus'); - }); it('should set the active item to the last option when UP key is pressed', () => { @@ -230,18 +225,17 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); const mention = fixture.componentInstance.mention; - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); fixture.componentInstance.trigger.onKeydown.emit(UP_ARROW_EVENT); fixture.detectChanges(); expect(optionEls[0].classList).not.toContain('focus'); expect(optionEls[4].classList).toContain('focus'); - }); it('should set the active item to the previous option when UP key is pressed', () => { @@ -250,11 +244,11 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); const mention = fixture.componentInstance.mention; - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); [1, 2, 3].forEach(() => fixture.componentInstance.trigger.onKeydown.emit(UP_ARROW_EVENT)); fixture.detectChanges(); @@ -272,13 +266,13 @@ describe('mention', () => { componentInstance.trigger.onKeydown.emit(DOWN_ARROW_EVENT); fixture.detectChanges(); - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; expect(optionEls[0].classList).not.toContain('focus'); expect(optionEls[1].classList).toContain('focus'); expect(optionEls[1].innerText).toEqual('ant-design'); - }); it('should set the active after filtering item when RIGHT/LEFT key is pressed', () => { @@ -290,14 +284,14 @@ describe('mention', () => { [1, 2, 3, 4].forEach(() => componentInstance.trigger.onKeydown.emit(RIGHT_EVENT)); fixture.detectChanges(); - const optionEls = - overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf; + const optionEls = overlayContainerElement.querySelectorAll('.ant-mention-dropdown-item') as NodeListOf< + HTMLElement + >; expect(optionEls[0].classList).toContain('focus'); expect(optionEls[1].classList).not.toContain('focus'); expect(optionEls[0].innerText).toEqual('ant-design'); expect(optionEls[1].innerText).toEqual('mention'); - }); it('should fill the text field when an option is selected with ENTER', fakeAsync(() => { @@ -312,12 +306,9 @@ describe('mention', () => { componentInstance.trigger.onKeydown.emit(ENTER_EVENT); fixture.detectChanges(); - expect(componentInstance.inputValue) - .toContain('@ant-design '); - - expect(textarea.value) - .toContain('@ant-design '); + expect(componentInstance.inputValue).toContain('@ant-design '); + expect(textarea.value).toContain('@ant-design '); })); it('should prevent the default enter key action', fakeAsync(() => { @@ -328,8 +319,7 @@ describe('mention', () => { flush(); fixture.componentInstance.trigger.onKeydown.emit(ENTER_EVENT); - expect(ENTER_EVENT.defaultPrevented) - .toBe(true); + expect(ENTER_EVENT.defaultPrevented).toBe(true); })); it('should not prevent the default enter action for a closed dropdown', () => { @@ -346,15 +336,13 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown')).toBeTruthy(); dispatchKeyboardEvent(textarea, 'keydown', TAB); fixture.detectChanges(); tick(500); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown')) - .toBeFalsy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown')).toBeFalsy(); })); it('should close the dropdown when pressing escape', fakeAsync(() => { @@ -362,17 +350,14 @@ describe('mention', () => { dispatchFakeEvent(textarea, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown')).toBeTruthy(); dispatchKeyboardEvent(textarea, 'keydown', ESCAPE); fixture.detectChanges(); tick(500); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown')) - .toBeFalsy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown')).toBeFalsy(); })); - }); describe('property', () => { @@ -395,13 +380,11 @@ describe('mention', () => { tick(); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown .anticon-loading')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown .anticon-loading')).toBeTruthy(); fixture.detectChanges(); flush(500); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown .anticon-loading')) - .toBeFalsy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown .anticon-loading')).toBeFalsy(); })); it('should open the dropdown when the type in @ prefix', () => { @@ -413,8 +396,7 @@ describe('mention', () => { const mention = fixture.componentInstance.mention; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); }); it('should open the dropdown when the type in # prefix', () => { @@ -426,8 +408,7 @@ describe('mention', () => { const mention = fixture.componentInstance.mention; - expect(mention.isOpen) - .toBe(true); + expect(mention.isOpen).toBe(true); }); it('should has the custom template in the dropdown', () => { @@ -435,33 +416,27 @@ describe('mention', () => { fixture.detectChanges(); typeInElement('@', textarea); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-mention-dropdown .custom')) - .toBeTruthy(); + expect(overlayContainerElement.querySelector('.ant-mention-dropdown .custom')).toBeTruthy(); }); it('should correct parsing the trigger content', () => { fixture.componentInstance.setArrayPrefix(); - typeInElement('ABC @Angular 123 @ant-design @你好 foo ant@gmail.com @@ng 123 .@.@ /@hello \\@hello #ng', textarea); + typeInElement( + 'ABC @Angular 123 @ant-design @你好 foo ant@gmail.com @@ng 123 .@.@ /@hello \\@hello #ng', + textarea + ); fixture.detectChanges(); - expect(fixture.componentInstance.mention.getMentions().join(',')) - .toBe('@Angular,@ant-design,@你好,@@ng,#ng'); + expect(fixture.componentInstance.mention.getMentions().join(',')).toBe('@Angular,@ant-design,@你好,@@ng,#ng'); }); - }); - }); @Component({ template: ` - - - + ` }) class NzTestSimpleMentionComponent { @@ -473,22 +448,19 @@ class NzTestSimpleMentionComponent { @Component({ template: ` - - - + + + {{ framework.name }} - {{ framework.type }} - - + + ` }) class NzTestPropertyMentionComponent { @@ -501,7 +473,7 @@ class NzTestPropertyMentionComponent { { name: 'Django', type: 'Python' } ]; loading = false; - prefix: string | string[] = '@'; + prefix: string | string[] = '@'; valueWith = (data: { name: string; type: string }) => data.name; @ViewChild(NzMentionComponent) mention: NzMentionComponent; @ViewChild(NzMentionTriggerDirective) trigger: NzMentionTriggerDirective; diff --git a/components/menu/demo/horizontal.ts b/components/menu/demo/horizontal.ts index 6a3abbe3809..93f740a6c6b 100755 --- a/components/menu/demo/horizontal.ts +++ b/components/menu/demo/horizontal.ts @@ -42,7 +42,7 @@ import { Component } from '@angular/core';
  • Navigation Four - Link
  • - ` + + ` }) -export class NzDemoMenuHorizontalComponent { -} +export class NzDemoMenuHorizontalComponent {} diff --git a/components/menu/demo/inline-collapsed.ts b/components/menu/demo/inline-collapsed.ts index 3fb531c247a..8feb33fc58e 100644 --- a/components/menu/demo/inline-collapsed.ts +++ b/components/menu/demo/inline-collapsed.ts @@ -5,9 +5,9 @@ import { Component } from '@angular/core'; template: `
    -
      +
      • diff --git a/components/menu/demo/inline.ts b/components/menu/demo/inline.ts index 79995c2b94a..7406794804d 100644 --- a/components/menu/demo/inline.ts +++ b/components/menu/demo/inline.ts @@ -54,7 +54,6 @@ import { Component } from '@angular/core';
      `, - styles : [] + styles: [] }) -export class NzDemoMenuInlineComponent { -} +export class NzDemoMenuInlineComponent {} diff --git a/components/menu/demo/recursive.ts b/components/menu/demo/recursive.ts index ff7d42019f1..c98918716de 100644 --- a/components/menu/demo/recursive.ts +++ b/components/menu/demo/recursive.ts @@ -4,103 +4,115 @@ import { Component } from '@angular/core'; selector: 'nz-demo-menu-recursive', template: `
        - + -
      • +
      • {{ menu.title }}
      • -
      • +
      • {{ menu.title }}
          - +
      • -
      `, - styles : [] +
    + `, + styles: [] }) export class NzDemoMenuRecursiveComponent { mode = false; dark = false; menus = [ { - 'level' : 1, - 'title' : 'Mail Group', - 'icon' : 'mail', - 'open' : true, - 'selected': false, - 'disabled': false, - 'children': [ + level: 1, + title: 'Mail Group', + icon: 'mail', + open: true, + selected: false, + disabled: false, + children: [ { - 'level' : 2, - 'title' : 'Group 1', - 'icon' : 'bars', - 'open' : false, - 'selected': false, - 'disabled': false, - 'children': [ + level: 2, + title: 'Group 1', + icon: 'bars', + open: false, + selected: false, + disabled: false, + children: [ { - 'level' : 3, - 'title' : 'Option 1', - 'selected': false, - 'disabled': false + level: 3, + title: 'Option 1', + selected: false, + disabled: false }, { - 'level' : 3, - 'title' : 'Option 2', - 'selected': false, - 'disabled': true + level: 3, + title: 'Option 2', + selected: false, + disabled: true } ] }, { - 'level' : 2, - 'title' : 'Group 2', - 'icon' : 'bars', - 'selected': true, - 'disabled': false + level: 2, + title: 'Group 2', + icon: 'bars', + selected: true, + disabled: false }, { - 'level' : 2, - 'title' : 'Group 3', - 'icon' : 'bars', - 'selected': false, - 'disabled': false + level: 2, + title: 'Group 3', + icon: 'bars', + selected: false, + disabled: false } ] }, { - 'level' : 1, - 'title' : 'Team Group', - 'icon' : 'team', - 'open' : false, - 'selected': false, - 'disabled': false, - 'children': [ + level: 1, + title: 'Team Group', + icon: 'team', + open: false, + selected: false, + disabled: false, + children: [ { - 'level' : 2, - 'title' : 'User 1', - 'icon' : 'user', - 'selected': false, - 'disabled': false + level: 2, + title: 'User 1', + icon: 'user', + selected: false, + disabled: false }, { - 'level' : 2, - 'title' : 'User 2', - 'icon' : 'user', - 'selected': false, - 'disabled': false + level: 2, + title: 'User 2', + icon: 'user', + selected: false, + disabled: false } ] } ]; - } diff --git a/components/menu/demo/sider-current.ts b/components/menu/demo/sider-current.ts index 3465fb89d95..ba2c6993b45 100644 --- a/components/menu/demo/sider-current.ts +++ b/components/menu/demo/sider-current.ts @@ -45,11 +45,12 @@ import { Component } from '@angular/core';
  • Option 11
  • - `, - styles : [] + + `, + styles: [] }) export class NzDemoMenuSiderCurrentComponent { - openMap: { [ name: string ]: boolean } = { + openMap: { [name: string]: boolean } = { sub1: true, sub2: false, sub3: false @@ -58,7 +59,7 @@ export class NzDemoMenuSiderCurrentComponent { openHandler(value: string): void { for (const key in this.openMap) { if (key !== value) { - this.openMap[ key ] = false; + this.openMap[key] = false; } } } diff --git a/components/menu/demo/switch-mode.ts b/components/menu/demo/switch-mode.ts index b357126b013..62e28aa3587 100644 --- a/components/menu/demo/switch-mode.ts +++ b/components/menu/demo/switch-mode.ts @@ -3,16 +3,14 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-menu-switch-mode', template: ` - - + Change Mode - - + Change Theme -
    -
    -
      +
      +
      +
      • Navigation One
          @@ -54,8 +52,9 @@ import { Component } from '@angular/core';
        • Option 11
      • -
      `, - styles : [] +
    + `, + styles: [] }) export class NzDemoMenuSwitchModeComponent { mode = false; diff --git a/components/menu/demo/theme.ts b/components/menu/demo/theme.ts index 0496cf9714f..a40ca6d2b18 100644 --- a/components/menu/demo/theme.ts +++ b/components/menu/demo/theme.ts @@ -6,9 +6,9 @@ import { Component } from '@angular/core'; Dark Light -
    -
    -
      +
      +
      +
      • Navigation One
          @@ -50,8 +50,9 @@ import { Component } from '@angular/core';
        • Option 11
      • -
      `, - styles : [] +
    + `, + styles: [] }) export class NzDemoMenuThemeComponent { theme = true; diff --git a/components/menu/demo/vertical.ts b/components/menu/demo/vertical.ts index 093ed7c0767..39664c30b95 100644 --- a/components/menu/demo/vertical.ts +++ b/components/menu/demo/vertical.ts @@ -44,8 +44,9 @@ import { Component } from '@angular/core';
  • Option 11
  • - `, - styles : [] + + `, + styles: [] }) export class NzDemoMenuVerticalComponent { change(value: boolean): void { diff --git a/components/menu/nz-menu-group.component.ts b/components/menu/nz-menu-group.component.ts index 58bdca8c9fb..f669d8b150b 100644 --- a/components/menu/nz-menu-group.component.ts +++ b/components/menu/nz-menu-group.component.ts @@ -1,10 +1,10 @@ import { ChangeDetectionStrategy, Component, ElementRef, Renderer2, ViewEncapsulation } from '@angular/core'; @Component({ - selector : '[nz-menu-group]', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-menu-group.component.html', + selector: '[nz-menu-group]', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-menu-group.component.html', preserveWhitespaces: false }) export class NzMenuGroupComponent { diff --git a/components/menu/nz-menu-item.directive.ts b/components/menu/nz-menu-item.directive.ts index a2144069730..a325639cb0d 100644 --- a/components/menu/nz-menu-item.directive.ts +++ b/components/menu/nz-menu-item.directive.ts @@ -19,9 +19,9 @@ import { NzMenuService } from './nz-menu.service'; import { NzSubmenuService } from './nz-submenu.service'; @Directive({ - selector : '[nz-menu-item]', - providers: [ NzUpdateHostClassService ], - host : { + selector: '[nz-menu-item]', + providers: [NzUpdateHostClassService], + host: { '(click)': 'clickMenuItem($event)' } }) @@ -50,9 +50,9 @@ export class NzMenuItemDirective implements OnInit, OnChanges, OnDestroy { setClassMap(): void { const prefixName = this.nzMenuService.isInDropDown ? 'ant-dropdown-menu-item' : 'ant-menu-item'; this.nzUpdateHostClassService.updateHostClass(this.el, { - [ `${prefixName}` ] : true, - [ `${prefixName}-selected` ]: this.nzSelected, - [ `${prefixName}-disabled` ]: this.nzDisabled + [`${prefixName}`]: true, + [`${prefixName}-selected`]: this.nzSelected, + [`${prefixName}-disabled`]: this.nzDisabled }); } @@ -62,12 +62,13 @@ export class NzMenuItemDirective implements OnInit, OnChanges, OnDestroy { this.setClassMap(); } - constructor(private nzUpdateHostClassService: NzUpdateHostClassService, - private nzMenuService: NzMenuService, - @Optional() private nzSubmenuService: NzSubmenuService, - private renderer: Renderer2, - private elementRef: ElementRef) { - } + constructor( + private nzUpdateHostClassService: NzUpdateHostClassService, + private nzMenuService: NzMenuService, + @Optional() private nzSubmenuService: NzSubmenuService, + private renderer: Renderer2, + private elementRef: ElementRef + ) {} ngOnInit(): void { /** store origin padding in padding */ @@ -79,26 +80,26 @@ export class NzMenuItemDirective implements OnInit, OnChanges, OnDestroy { this.nzMenuService.mode$, this.nzMenuService.inlineIndent$, this.nzSubmenuService ? this.nzSubmenuService.level$ : EMPTY - ).pipe( - takeUntil(this.destroy$) - ).subscribe(() => { - let padding: number | null = null; - if (this.nzMenuService.mode === 'inline') { - if (isNotNil(this.nzPaddingLeft)) { - padding = this.nzPaddingLeft; + ) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + let padding: number | null = null; + if (this.nzMenuService.mode === 'inline') { + if (isNotNil(this.nzPaddingLeft)) { + padding = this.nzPaddingLeft; + } else { + const level = this.nzSubmenuService ? this.nzSubmenuService.level + 1 : 1; + padding = level * this.nzMenuService.inlineIndent; + } } else { - const level = this.nzSubmenuService ? this.nzSubmenuService.level + 1 : 1; - padding = level * this.nzMenuService.inlineIndent; + padding = this.originalPadding; } - } else { - padding = this.originalPadding; - } - if (padding) { - this.renderer.setStyle(this.el, 'padding-left', `${padding}px`); - } else { - this.renderer.removeStyle(this.el, 'padding-left'); - } - }); + if (padding) { + this.renderer.setStyle(this.el, 'padding-left', `${padding}px`); + } else { + this.renderer.removeStyle(this.el, 'padding-left'); + } + }); this.setClassMap(); } @@ -115,5 +116,4 @@ export class NzMenuItemDirective implements OnInit, OnChanges, OnDestroy { this.destroy$.next(); this.destroy$.complete(); } - } diff --git a/components/menu/nz-menu.directive.ts b/components/menu/nz-menu.directive.ts index 7b6b052aafb..4cedadad1b7 100644 --- a/components/menu/nz-menu.directive.ts +++ b/components/menu/nz-menu.directive.ts @@ -30,30 +30,24 @@ export function NzMenuFactory(dropService: NzMenuDropdownService, menuService: N } @Directive({ - selector : '[nz-menu]', + selector: '[nz-menu]', providers: [ NzUpdateHostClassService, NzMenuMenuService, { - provide : NzMenuService, + provide: NzMenuService, useFactory: NzMenuFactory, - deps : [ - [ - new SkipSelf(), - new Optional(), - NzMenuDropdownService - ], - NzMenuMenuService - ] + deps: [[new SkipSelf(), new Optional(), NzMenuDropdownService], NzMenuMenuService] } ] }) - export class NzMenuDirective implements AfterContentInit, OnInit, OnChanges, OnDestroy { private destroy$ = new Subject(); private cacheMode: NzDirectionVHIType; private listOfOpenedNzSubMenuComponent: NzSubMenuComponent[] = []; - @ContentChildren(NzMenuItemDirective, { descendants: true }) listOfNzMenuItemDirective: QueryList; + @ContentChildren(NzMenuItemDirective, { descendants: true }) listOfNzMenuItemDirective: QueryList< + NzMenuItemDirective + >; @ContentChildren(NzSubMenuComponent, { descendants: true }) listOfNzSubMenuComponent: QueryList; @Input() nzInlineIndent = 24; @Input() nzTheme: 'light' | 'dark' = 'light'; @@ -81,25 +75,23 @@ export class NzMenuDirective implements AfterContentInit, OnInit, OnChanges, OnD setClassMap(): void { const prefixName = this.nzMenuService.isInDropDown ? 'ant-dropdown-menu' : 'ant-menu'; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ `${prefixName}` ] : true, - [ `${prefixName}-root` ] : true, - [ `${prefixName}-${this.nzTheme}` ] : true, - [ `${prefixName}-${this.nzMode}` ] : true, - [ `${prefixName}-inline-collapsed` ]: this.nzInlineCollapsed + [`${prefixName}`]: true, + [`${prefixName}-root`]: true, + [`${prefixName}-${this.nzTheme}`]: true, + [`${prefixName}-${this.nzMode}`]: true, + [`${prefixName}-inline-collapsed`]: this.nzInlineCollapsed }); } - constructor(public elementRef: ElementRef, - private nzMenuService: NzMenuService, - private nzUpdateHostClassService: NzUpdateHostClassService) { - - } + constructor( + public elementRef: ElementRef, + private nzMenuService: NzMenuService, + private nzUpdateHostClassService: NzUpdateHostClassService + ) {} ngOnInit(): void { this.setClassMap(); - this.nzMenuService.menuItemClick$.pipe( - takeUntil(this.destroy$) - ).subscribe(menu => { + this.nzMenuService.menuItemClick$.pipe(takeUntil(this.destroy$)).subscribe(menu => { this.nzClick.emit(menu); if (this.nzSelectable) { this.listOfNzMenuItemDirective.forEach(item => item.setSelectedState(item === menu)); diff --git a/components/menu/nz-menu.module.ts b/components/menu/nz-menu.module.ts index d5ee1bb96fd..363dad81965 100644 --- a/components/menu/nz-menu.module.ts +++ b/components/menu/nz-menu.module.ts @@ -14,9 +14,14 @@ import { NzMenuDirective } from '../menu/nz-menu.directive'; import { NzSubMenuComponent } from '../menu/nz-submenu.component'; @NgModule({ - imports : [ CommonModule, FormsModule, NzButtonModule, OverlayModule, NzIconModule, NzNoAnimationModule ], - declarations: [ NzMenuDirective, NzMenuItemDirective, NzSubMenuComponent, NzMenuDividerDirective, NzMenuGroupComponent ], - exports : [ NzMenuDirective, NzMenuItemDirective, NzSubMenuComponent, NzMenuDividerDirective, NzMenuGroupComponent ] + imports: [CommonModule, FormsModule, NzButtonModule, OverlayModule, NzIconModule, NzNoAnimationModule], + declarations: [ + NzMenuDirective, + NzMenuItemDirective, + NzSubMenuComponent, + NzMenuDividerDirective, + NzMenuGroupComponent + ], + exports: [NzMenuDirective, NzMenuItemDirective, NzSubMenuComponent, NzMenuDividerDirective, NzMenuGroupComponent] }) -export class NzMenuModule { -} +export class NzMenuModule {} diff --git a/components/menu/nz-menu.spec.ts b/components/menu/nz-menu.spec.ts index fdd275e96a3..4ae825834ea 100644 --- a/components/menu/nz-menu.spec.ts +++ b/components/menu/nz-menu.spec.ts @@ -36,10 +36,20 @@ describe('menu', () => { beforeEach(async(() => { const dir = 'ltr'; TestBed.configureTestingModule({ - imports : [ NzMenuModule, NoopAnimationsModule, NoopAnimationsModule, NzIconTestModule ], - declarations: [ NzDemoMenuHorizontalComponent, NzDemoMenuInlineComponent, NzDemoMenuInlineCollapsedComponent, NzDemoMenuSiderCurrentComponent, NzDemoMenuThemeComponent, NzDemoMenuSwitchModeComponent, NzTestMenuHorizontalComponent, NzTestMenuInlineComponent, NzDemoMenuNgForComponent ], - schemas : [ NO_ERRORS_SCHEMA ], - providers : [ + imports: [NzMenuModule, NoopAnimationsModule, NoopAnimationsModule, NzIconTestModule], + declarations: [ + NzDemoMenuHorizontalComponent, + NzDemoMenuInlineComponent, + NzDemoMenuInlineCollapsedComponent, + NzDemoMenuSiderCurrentComponent, + NzDemoMenuThemeComponent, + NzDemoMenuSwitchModeComponent, + NzTestMenuHorizontalComponent, + NzTestMenuInlineComponent, + NzDemoMenuNgForComponent + ], + schemas: [NO_ERRORS_SCHEMA], + providers: [ { provide: Directionality, useFactory: () => ({ value: dir }) }, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject }) } ] @@ -47,13 +57,13 @@ describe('menu', () => { TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -72,22 +82,22 @@ describe('menu', () => { it('should className correct', () => { fixture.detectChanges(); expect(items.every(item => item.nativeElement.classList.contains('ant-menu-item'))).toBe(true); - expect(items[ 1 ].nativeElement.classList.contains('ant-menu-item-disabled')).toBe(true); + expect(items[1].nativeElement.classList.contains('ant-menu-item-disabled')).toBe(true); expect(submenu.nativeElement.classList.contains('ant-menu-submenu-horizontal')).toBe(true); expect(submenu.nativeElement.classList.contains('ant-menu-submenu')).toBe(true); expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-light ant-menu-horizontal'); }); it('should menu item select', () => { fixture.detectChanges(); - items[ 0 ].nativeElement.click(); + items[0].nativeElement.click(); fixture.detectChanges(); - expect(items[ 0 ].nativeElement.classList.contains('ant-menu-item-selected')).toBe(true); + expect(items[0].nativeElement.classList.contains('ant-menu-item-selected')).toBe(true); }); it('should menu disabled work', () => { fixture.detectChanges(); - items[ 1 ].nativeElement.click(); + items[1].nativeElement.click(); fixture.detectChanges(); - expect(items[ 0 ].nativeElement.classList.contains('ant-menu-item-selected')).toBe(false); + expect(items[0].nativeElement.classList.contains('ant-menu-item-selected')).toBe(false); }); }); describe('inline', () => { @@ -104,7 +114,9 @@ describe('menu', () => { it('should className correct', () => { fixture.detectChanges(); expect(submenus.every(subitem => subitem.nativeElement.classList.contains('ant-menu-submenu'))).toBe(true); - expect(submenus.every(subitem => subitem.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe(true); + expect(submenus.every(subitem => subitem.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe( + true + ); expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-light ant-menu-inline'); }); it('should padding left work', () => { @@ -116,19 +128,19 @@ describe('menu', () => { }); it('should click expand', fakeAsync(() => { fixture.detectChanges(); - const ul = submenus[ 0 ].nativeElement.querySelector('.ant-menu'); - const title = submenus[ 0 ].nativeElement.querySelector('.ant-menu-submenu-title'); + const ul = submenus[0].nativeElement.querySelector('.ant-menu'); + const title = submenus[0].nativeElement.querySelector('.ant-menu-submenu-title'); expect(ul.style.height).toBe('0px'); title.click(); fixture.detectChanges(); tick(500); expect(ul.style.height).not.toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); title.click(); fixture.detectChanges(); tick(500); expect(ul.style.height).toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); })); }); describe('inline-collapsed', () => { @@ -147,21 +159,23 @@ describe('menu', () => { expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-dark ant-menu-inline'); testComponent.isCollapsed = true; fixture.detectChanges(); - expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-dark ant-menu-vertical ant-menu-inline-collapsed'); + expect(menu.nativeElement.className).toBe( + 'ant-menu ant-menu-root ant-menu-dark ant-menu-vertical ant-menu-inline-collapsed' + ); testComponent.isCollapsed = false; fixture.detectChanges(); expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-dark ant-menu-inline'); }); it('should keep open after change mode', () => { fixture.detectChanges(); - let ul = submenus[ 0 ].nativeElement.querySelector('.ant-menu'); - const title = submenus[ 0 ].nativeElement.querySelector('.ant-menu-submenu-title'); + let ul = submenus[0].nativeElement.querySelector('.ant-menu'); + const title = submenus[0].nativeElement.querySelector('.ant-menu-submenu-title'); expect(ul.style.height).toBe('0px'); testComponent.isCollapsed = true; fixture.detectChanges(); testComponent.isCollapsed = false; fixture.detectChanges(); - ul = submenus[ 0 ].nativeElement.querySelector('.ant-menu'); + ul = submenus[0].nativeElement.querySelector('.ant-menu'); expect(ul.style.height).toBe('0px'); title.click(); fixture.detectChanges(); @@ -182,34 +196,34 @@ describe('menu', () => { }); it('should collapsed self work', fakeAsync(() => { fixture.detectChanges(); - const ul = submenus[ 0 ].nativeElement.querySelector('.ant-menu'); - const title = submenus[ 0 ].nativeElement.querySelector('.ant-menu-submenu-title'); + const ul = submenus[0].nativeElement.querySelector('.ant-menu'); + const title = submenus[0].nativeElement.querySelector('.ant-menu-submenu-title'); expect(ul.style.height).not.toBe('0px'); title.click(); fixture.detectChanges(); tick(500); expect(ul.style.height).toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); title.click(); fixture.detectChanges(); tick(500); expect(ul.style.height).not.toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); })); it('should collapsed other work', fakeAsync(() => { fixture.detectChanges(); - const firstUl = submenus[ 0 ].nativeElement.querySelector('.ant-menu'); - const secondUl = submenus[ 1 ].nativeElement.querySelector('.ant-menu'); - const secondTitle = submenus[ 1 ].nativeElement.querySelector('.ant-menu-submenu-title'); + const firstUl = submenus[0].nativeElement.querySelector('.ant-menu'); + const secondUl = submenus[1].nativeElement.querySelector('.ant-menu'); + const secondTitle = submenus[1].nativeElement.querySelector('.ant-menu-submenu-title'); expect(firstUl.style.height).not.toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); secondTitle.click(); fixture.detectChanges(); tick(500); expect(firstUl.style.height).toBe('0px'); - expect(submenus[ 0 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); + expect(submenus[0].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(false); expect(secondUl.style.height).not.toBe('0px'); - expect(submenus[ 1 ].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); + expect(submenus[1].nativeElement.classList.contains('ant-menu-submenu-open')).toBe(true); })); }); describe('theme', () => { @@ -243,12 +257,18 @@ describe('menu', () => { it('should className correct', () => { fixture.detectChanges(); expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-light ant-menu-inline'); - expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe(true); + expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe( + true + ); testComponent.mode = true; fixture.detectChanges(); expect(menu.nativeElement.className).toBe('ant-menu ant-menu-root ant-menu-light ant-menu-vertical'); - expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe(false); - expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-vertical'))).toBe(true); + expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-inline'))).toBe( + false + ); + expect(submenus.every(submenu => submenu.nativeElement.classList.contains('ant-menu-submenu-vertical'))).toBe( + true + ); }); }); }); @@ -274,7 +294,7 @@ describe('menu', () => { const mouseenterCallback = jasmine.createSpy('mouseenter callback'); const subs = testComponent.subs.toArray(); const title = submenu.nativeElement.querySelector('.ant-menu-submenu-title'); - subs[ 0 ].nzSubmenuService.mouseEnterLeave$.subscribe(mouseenterCallback); + subs[0].nzSubmenuService.mouseEnterLeave$.subscribe(mouseenterCallback); dispatchFakeEvent(title, 'mouseenter'); fixture.detectChanges(); expect(mouseenterCallback).toHaveBeenCalledWith(true); @@ -285,7 +305,7 @@ describe('menu', () => { const mouseleaveCallback = jasmine.createSpy('mouseleave callback'); const subs = testComponent.subs.toArray(); const title = submenu.nativeElement.querySelector('.ant-menu-submenu-title'); - subs[ 0 ].nzSubmenuService.mouseEnterLeave$.subscribe(mouseleaveCallback); + subs[0].nzSubmenuService.mouseEnterLeave$.subscribe(mouseleaveCallback); dispatchFakeEvent(title, 'mouseleave'); fixture.detectChanges(); expect(mouseleaveCallback).toHaveBeenCalledWith(false); @@ -296,9 +316,9 @@ describe('menu', () => { fixture.detectChanges(); const nestedCallback = jasmine.createSpy('nested callback'); const subs = testComponent.subs.toArray(); - subs[ 0 ].nzSubmenuService.subMenuOpen$.subscribe(nestedCallback); - subs[ 1 ].nzOpen = true; - subs[ 1 ].nzSubmenuService.open$.next(false); + subs[0].nzSubmenuService.subMenuOpen$.subscribe(nestedCallback); + subs[1].nzOpen = true; + subs[1].nzSubmenuService.open$.next(false); fixture.detectChanges(); expect(nestedCallback).toHaveBeenCalledWith(false); expect(nestedCallback).toHaveBeenCalledTimes(1); @@ -309,9 +329,9 @@ describe('menu', () => { fixture.detectChanges(); const nestedCallback = jasmine.createSpy('nested callback'); const subs = testComponent.subs.toArray(); - subs[ 0 ].nzSubmenuService.subMenuOpen$.subscribe(nestedCallback); - subs[ 1 ].nzOpen = true; - subs[ 1 ].nzSubmenuService.open$.next(false); + subs[0].nzSubmenuService.subMenuOpen$.subscribe(nestedCallback); + subs[1].nzOpen = true; + subs[1].nzSubmenuService.open$.next(false); fixture.detectChanges(); expect(nestedCallback).toHaveBeenCalledTimes(1); }); @@ -320,9 +340,9 @@ describe('menu', () => { fixture.detectChanges(); const nestedCallback = jasmine.createSpy('nested callback'); const subs = testComponent.subs.toArray(); - subs[ 1 ].nzOpen = true; + subs[1].nzOpen = true; fixture.detectChanges(); - subs[ 1 ].nzSubmenuService.mouseEnterLeave$.subscribe(nestedCallback); + subs[1].nzSubmenuService.mouseEnterLeave$.subscribe(nestedCallback); testComponent.menuitem.nativeElement.click(); fixture.detectChanges(); expect(nestedCallback).toHaveBeenCalledWith(false); @@ -333,8 +353,8 @@ describe('menu', () => { fixture.detectChanges(); const nestedCallback = jasmine.createSpy('nested callback'); const subs = testComponent.subs.toArray(); - subs[ 1 ].nzSubmenuService.mouseEnterLeave$.subscribe(nestedCallback); - subs[ 1 ].nzOpen = true; + subs[1].nzSubmenuService.mouseEnterLeave$.subscribe(nestedCallback); + subs[1].nzOpen = true; testComponent.disableditem.nativeElement.click(); fixture.detectChanges(); expect(nestedCallback).toHaveBeenCalledTimes(0); @@ -356,16 +376,16 @@ describe('menu', () => { it('should position change correct', () => { const fakeLeftTopEvent = { connectionPair: { - originX : 'start', - originY : 'top', + originX: 'start', + originY: 'top', overlayX: 'end', overlayY: 'top' } } as ConnectedOverlayPositionChange; const fakeRightTopEvent = { connectionPair: { - originX : 'end', - originY : 'top', + originX: 'end', + originY: 'top', overlayX: 'start', overlayY: 'top' } @@ -373,14 +393,14 @@ describe('menu', () => { fixture.detectChanges(); testComponent.open = true; const subs = testComponent.subs.toArray(); - subs[ 1 ].nzOpen = true; + subs[1].nzOpen = true; fixture.detectChanges(); - subs[ 1 ].onPositionChange(fakeLeftTopEvent); + subs[1].onPositionChange(fakeLeftTopEvent); fixture.detectChanges(); - expect(subs[ 1 ].placement).toBe('leftTop'); - subs[ 1 ].onPositionChange(fakeRightTopEvent); + expect(subs[1].placement).toBe('leftTop'); + subs[1].onPositionChange(fakeRightTopEvent); fixture.detectChanges(); - expect(subs[ 1 ].placement).toBe('rightTop'); + expect(subs[1].placement).toBe('rightTop'); }); }); describe('inline submenu', () => { @@ -486,7 +506,7 @@ export class NzTestMenuHorizontalComponent { `, - styles : [] + styles: [] }) export class NzTestMenuInlineComponent { disabled = false; @@ -500,29 +520,28 @@ export class NzTestMenuInlineComponent { template: `
    • - {{l1.text}} + {{ l1.text }}
      • - {{l2.text}} + {{ l2.text }}
          -
        • {{l3.text}}
        • +
        • {{ l3.text }}
    • -
    `, - styles : [] + + `, + styles: [] }) export class NzDemoMenuNgForComponent { menus = [ { - text : 'level1', + text: 'level1', children: [ { - text : 'level2', - children: [ - { text: 'level3' } - ] + text: 'level2', + children: [{ text: 'level3' }] } ] } diff --git a/components/menu/nz-submenu.component.ts b/components/menu/nz-submenu.component.ts index 678782e1200..8d3425962cf 100644 --- a/components/menu/nz-submenu.component.ts +++ b/components/menu/nz-submenu.component.ts @@ -34,15 +34,15 @@ import { NzMenuService } from './nz-menu.service'; import { NzSubmenuService } from './nz-submenu.service'; @Component({ - selector : '[nz-submenu]', - providers : [ NzSubmenuService, NzUpdateHostClassService ], - animations : [ collapseMotion, zoomBigMotion, slideMotion ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, + selector: '[nz-submenu]', + providers: [NzSubmenuService, NzUpdateHostClassService], + animations: [collapseMotion, zoomBigMotion, slideMotion], + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, - templateUrl : './nz-submenu.component.html', - styles : [ - ` + templateUrl: './nz-submenu.component.html', + styles: [ + ` .ant-menu-submenu-placement-bottomLeft { top: 6px; position: relative; @@ -60,16 +60,17 @@ import { NzSubmenuService } from './nz-submenu.service'; ` ] }) - export class NzSubMenuComponent implements OnInit, OnDestroy, AfterContentInit, OnChanges { placement = 'rightTop'; triggerWidth: number; expandState = 'collapsed'; - overlayPositions = [ ...DEFAULT_SUBMENU_POSITIONS ]; + overlayPositions = [...DEFAULT_SUBMENU_POSITIONS]; private destroy$ = new Subject(); private isChildMenuSelected = false; @ContentChildren(NzSubMenuComponent, { descendants: true }) listOfNzSubMenuComponent: QueryList; - @ContentChildren(NzMenuItemDirective, { descendants: true }) listOfNzMenuItemDirective: QueryList; + @ContentChildren(NzMenuItemDirective, { descendants: true }) listOfNzMenuItemDirective: QueryList< + NzMenuItemDirective + >; @ViewChild(CdkConnectedOverlay) cdkConnectedOverlay: CdkConnectedOverlay; @ViewChild(CdkOverlayOrigin, { read: ElementRef }) cdkOverlayOrigin: ElementRef; @Input() nzPaddingLeft: number; @@ -105,51 +106,48 @@ export class NzSubMenuComponent implements OnInit, OnDestroy, AfterContentInit, setClassMap(): void { const prefixName = this.nzMenuService.isInDropDown ? 'ant-dropdown-menu-submenu' : 'ant-menu-submenu'; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ `${prefixName}` ] : true, - [ `${prefixName}-disabled` ] : this.nzDisabled, - [ `${prefixName}-open` ] : this.nzOpen, - [ `${prefixName}-selected` ] : this.isChildMenuSelected, - [ `${prefixName}-${this.nzSubmenuService.mode}` ]: true + [`${prefixName}`]: true, + [`${prefixName}-disabled`]: this.nzDisabled, + [`${prefixName}-open`]: this.nzOpen, + [`${prefixName}-selected`]: this.isChildMenuSelected, + [`${prefixName}-${this.nzSubmenuService.mode}`]: true }); } - constructor(private elementRef: ElementRef, - public nzMenuService: NzMenuService, - private cdr: ChangeDetectorRef, - public nzSubmenuService: NzSubmenuService, - private nzUpdateHostClassService: NzUpdateHostClassService, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + constructor( + private elementRef: ElementRef, + public nzMenuService: NzMenuService, + private cdr: ChangeDetectorRef, + public nzSubmenuService: NzSubmenuService, + private nzUpdateHostClassService: NzUpdateHostClassService, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngOnInit(): void { - combineLatest( - this.nzSubmenuService.mode$, - this.nzSubmenuService.open$ - ).pipe( - takeUntil(this.destroy$) - ).subscribe(data => { - const mode = data[ 0 ]; - const open = data[ 1 ]; - if (open && mode === 'inline') { - this.expandState = 'expanded'; - } else if (open && mode === 'horizontal') { - this.expandState = 'bottom'; - } else if (open && mode === 'vertical') { - this.expandState = 'active'; - } else { - this.expandState = 'collapsed'; - } - this.overlayPositions = mode === 'horizontal' ? [ POSITION_MAP.bottomLeft ] : [ POSITION_MAP.rightTop, POSITION_MAP.leftTop ]; - if (open !== this.nzOpen) { - this.nzOpen = open; - this.nzOpenChange.emit(this.nzOpen); - } - this.setClassMap(); - this.setTriggerWidth(); - }); - this.nzSubmenuService.menuOpen$.pipe( - takeUntil(this.destroy$) - ).subscribe((data: boolean) => { + combineLatest(this.nzSubmenuService.mode$, this.nzSubmenuService.open$) + .pipe(takeUntil(this.destroy$)) + .subscribe(data => { + const mode = data[0]; + const open = data[1]; + if (open && mode === 'inline') { + this.expandState = 'expanded'; + } else if (open && mode === 'horizontal') { + this.expandState = 'bottom'; + } else if (open && mode === 'vertical') { + this.expandState = 'active'; + } else { + this.expandState = 'collapsed'; + } + this.overlayPositions = + mode === 'horizontal' ? [POSITION_MAP.bottomLeft] : [POSITION_MAP.rightTop, POSITION_MAP.leftTop]; + if (open !== this.nzOpen) { + this.nzOpen = open; + this.nzOpenChange.emit(this.nzOpen); + } + this.setClassMap(); + this.setTriggerWidth(); + }); + this.nzSubmenuService.menuOpen$.pipe(takeUntil(this.destroy$)).subscribe((data: boolean) => { this.nzMenuService.menuOpen$.next(data); }); merge( @@ -157,27 +155,29 @@ export class NzSubMenuComponent implements OnInit, OnDestroy, AfterContentInit, this.nzMenuService.inlineIndent$, this.nzSubmenuService.level$, this.nzSubmenuService.open$, - this.nzSubmenuService.mode$).pipe( - takeUntil(this.destroy$) - ).subscribe(() => { - this.cdr.markForCheck(); - }); + this.nzSubmenuService.mode$ + ) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + this.cdr.markForCheck(); + }); } ngAfterContentInit(): void { this.setTriggerWidth(); - this.listOfNzMenuItemDirective.changes.pipe( - startWith(true), - flatMap(() => merge( - this.listOfNzMenuItemDirective.changes, - ...this.listOfNzMenuItemDirective.map(menu => menu.selected$) - )), - map(() => this.listOfNzMenuItemDirective.some(e => e.nzSelected)), - takeUntil(this.destroy$) - ).subscribe((selected) => { - this.isChildMenuSelected = selected; - this.setClassMap(); - }); + this.listOfNzMenuItemDirective.changes + .pipe( + startWith(true), + flatMap(() => + merge(this.listOfNzMenuItemDirective.changes, ...this.listOfNzMenuItemDirective.map(menu => menu.selected$)) + ), + map(() => this.listOfNzMenuItemDirective.some(e => e.nzSelected)), + takeUntil(this.destroy$) + ) + .subscribe(selected => { + this.isChildMenuSelected = selected; + this.setClassMap(); + }); } ngOnChanges(changes: SimpleChanges): void { diff --git a/components/menu/nz-submenu.service.ts b/components/menu/nz-submenu.service.ts index b93c9ff4008..91c67ad276a 100644 --- a/components/menu/nz-submenu.service.ts +++ b/components/menu/nz-submenu.service.ts @@ -18,18 +18,15 @@ export class NzSubmenuService { return 'horizontal'; } }), - tap(mode => this.mode = mode as NzDirectionVHIType) + tap(mode => (this.mode = mode as NzDirectionVHIType)) ); level = 1; level$ = new BehaviorSubject(1); subMenuOpen$ = new BehaviorSubject(false); open$ = new BehaviorSubject(false); mouseEnterLeave$ = new Subject(); - menuOpen$ = combineLatest( - this.subMenuOpen$, - this.mouseEnterLeave$ - ).pipe( - map(value => value[ 0 ] || value[ 1 ]), + menuOpen$ = combineLatest(this.subMenuOpen$, this.mouseEnterLeave$).pipe( + map(value => value[0] || value[1]), auditTime(150), distinctUntilChanged(), tap(data => { @@ -59,7 +56,10 @@ export class NzSubmenuService { } } - constructor(@SkipSelf() @Optional() private nzHostSubmenuService: NzSubmenuService, public nzMenuService: NzMenuService) { + constructor( + @SkipSelf() @Optional() private nzHostSubmenuService: NzSubmenuService, + public nzMenuService: NzMenuService + ) { if (this.nzHostSubmenuService) { this.setLevel(this.nzHostSubmenuService.level + 1); } diff --git a/components/message/demo/close.ts b/components/message/demo/close.ts index 698d8a3857f..0a6e99ead31 100644 --- a/components/message/demo/close.ts +++ b/components/message/demo/close.ts @@ -7,18 +7,20 @@ import { concatMap } from 'rxjs/operators'; template: ` `, - styles : [] + styles: [] }) export class NzDemoMessageCloseComponent { - constructor(private message: NzMessageService) { - } + constructor(private message: NzMessageService) {} startShowMessages(): void { - this.message.loading('Action in progress', { nzDuration: 2500 }).onClose!.pipe( - concatMap(() => this.message.success('Loading finished', { nzDuration: 2500 }).onClose!), - concatMap(() => this.message.info('Loading finished is finished', { nzDuration: 2500 }).onClose!) - ).subscribe(() => { - console.log('All completed!'); - }); + this.message + .loading('Action in progress', { nzDuration: 2500 }) + .onClose!.pipe( + concatMap(() => this.message.success('Loading finished', { nzDuration: 2500 }).onClose!), + concatMap(() => this.message.info('Loading finished is finished', { nzDuration: 2500 }).onClose!) + ) + .subscribe(() => { + console.log('All completed!'); + }); } } diff --git a/components/message/demo/duration.ts b/components/message/demo/duration.ts index ef3da3d90cb..38e9efa94c5 100644 --- a/components/message/demo/duration.ts +++ b/components/message/demo/duration.ts @@ -6,13 +6,14 @@ import { NzMessageService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoMessageDurationComponent { createBasicMessage(): void { - this.message.success('This is a prompt message for success, and it will disappear in 10 seconds', { nzDuration: 10000 }); + this.message.success('This is a prompt message for success, and it will disappear in 10 seconds', { + nzDuration: 10000 + }); } - constructor(private message: NzMessageService) { - } -} \ No newline at end of file + constructor(private message: NzMessageService) {} +} diff --git a/components/message/demo/info.ts b/components/message/demo/info.ts index 42d51ee7ed4..2ff24a21eb8 100644 --- a/components/message/demo/info.ts +++ b/components/message/demo/info.ts @@ -6,12 +6,10 @@ import { NzMessageService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoMessageInfoComponent { - - constructor(private message: NzMessageService) { - } + constructor(private message: NzMessageService) {} createBasicMessage(): void { this.message.info('This is a normal message'); diff --git a/components/message/demo/loading.ts b/components/message/demo/loading.ts index b011a8187ae..c881f8487af 100644 --- a/components/message/demo/loading.ts +++ b/components/message/demo/loading.ts @@ -6,12 +6,10 @@ import { NzMessageService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoMessageLoadingComponent { - - constructor(private message: NzMessageService) { - } + constructor(private message: NzMessageService) {} createBasicMessage(): void { const id = this.message.loading('Action in progress..', { nzDuration: 0 }).messageId; diff --git a/components/message/demo/other.ts b/components/message/demo/other.ts index 8fbb64c9392..dc1aefeb3fa 100644 --- a/components/message/demo/other.ts +++ b/components/message/demo/other.ts @@ -8,8 +8,8 @@ import { NzMessageService } from 'ng-zorro-antd'; `, - styles : [ - ` + styles: [ + ` [nz-button] { margin-right: 8px; } @@ -21,6 +21,5 @@ export class NzDemoMessageOtherComponent { this.message.create(type, `This is a message of ${type}`); } - constructor(private message: NzMessageService) { - } + constructor(private message: NzMessageService) {} } diff --git a/components/message/nz-message-config.ts b/components/message/nz-message-config.ts index daa5fe3b42c..7f1a8137d66 100644 --- a/components/message/nz-message-config.ts +++ b/components/message/nz-message-config.ts @@ -15,12 +15,12 @@ export const NZ_MESSAGE_DEFAULT_CONFIG = new InjectionToken('NZ export const NZ_MESSAGE_CONFIG = new InjectionToken('NZ_MESSAGE_CONFIG'); export const NZ_MESSAGE_DEFAULT_CONFIG_PROVIDER = { - provide : NZ_MESSAGE_DEFAULT_CONFIG, + provide: NZ_MESSAGE_DEFAULT_CONFIG, useValue: { - nzAnimate : true, - nzDuration : 3000, - nzMaxStack : 7, + nzAnimate: true, + nzDuration: 3000, + nzMaxStack: 7, nzPauseOnHover: true, - nzTop : 24 + nzTop: 24 } }; diff --git a/components/message/nz-message-container.component.ts b/components/message/nz-message-container.component.ts index 06ded53a711..11d9003dbec 100644 --- a/components/message/nz-message-container.component.ts +++ b/components/message/nz-message-container.component.ts @@ -10,22 +10,15 @@ import { Subject } from 'rxjs'; import { toCssPixel } from '../core/util'; -import { - NzMessageConfig, - NZ_MESSAGE_CONFIG, - NZ_MESSAGE_DEFAULT_CONFIG -} from './nz-message-config'; -import { - NzMessageDataFilled, - NzMessageDataOptions -} from './nz-message.definitions'; +import { NzMessageConfig, NZ_MESSAGE_CONFIG, NZ_MESSAGE_DEFAULT_CONFIG } from './nz-message-config'; +import { NzMessageDataFilled, NzMessageDataOptions } from './nz-message.definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-message-container', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-message-container', preserveWhitespaces: false, - templateUrl : './nz-message-container.component.html' + templateUrl: './nz-message-container.component.html' }) export class NzMessageContainerComponent { messages: NzMessageDataFilled[] = []; @@ -92,10 +85,10 @@ export class NzMessageContainerComponent { */ protected _mergeMessageOptions(options?: NzMessageDataOptions): NzMessageDataOptions { const defaultOptions: NzMessageDataOptions = { - nzDuration : this.config.nzDuration, - nzAnimate : this.config.nzAnimate, + nzDuration: this.config.nzDuration, + nzAnimate: this.config.nzAnimate, nzPauseOnHover: this.config.nzPauseOnHover }; - return { ...defaultOptions, ...options}; + return { ...defaultOptions, ...options }; } } diff --git a/components/message/nz-message.component.ts b/components/message/nz-message.component.ts index e5076ba4982..42cc03d4ab7 100644 --- a/components/message/nz-message.component.ts +++ b/components/message/nz-message.component.ts @@ -12,12 +12,12 @@ import { NzMessageContainerComponent } from './nz-message-container.component'; import { NzMessageDataFilled, NzMessageDataOptions } from './nz-message.definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-message', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-message', preserveWhitespaces: false, - animations : [ moveUpMotion ], - templateUrl : './nz-message.component.html' + animations: [moveUpMotion], + templateUrl: './nz-message.component.html' }) export class NzMessageComponent implements OnInit, OnDestroy { @Input() nzMessage: NzMessageDataFilled; @@ -30,11 +30,7 @@ export class NzMessageComponent implements OnInit, OnDestroy { private _eraseTimingStart: number; private _eraseTTL: number; // Time to live. - constructor( - private _messageContainer: NzMessageContainerComponent, - protected cdr: ChangeDetectorRef - ) { - } + constructor(private _messageContainer: NzMessageContainerComponent, protected cdr: ChangeDetectorRef) {} ngOnInit(): void { // `NzMessageContainer` does its job so all properties cannot be undefined. diff --git a/components/message/nz-message.module.ts b/components/message/nz-message.module.ts index f797cb3d3fe..cbaf4dc77f8 100644 --- a/components/message/nz-message.module.ts +++ b/components/message/nz-message.module.ts @@ -10,10 +10,9 @@ import { NzMessageComponent } from './nz-message.component'; import { NzMessageService } from './nz-message.service'; @NgModule({ - imports : [ CommonModule, OverlayModule, NzIconModule, NzAddOnModule ], - declarations : [ NzMessageContainerComponent, NzMessageComponent ], - providers : [ NZ_MESSAGE_DEFAULT_CONFIG_PROVIDER, NzMessageService ], - entryComponents: [ NzMessageContainerComponent ] + imports: [CommonModule, OverlayModule, NzIconModule, NzAddOnModule], + declarations: [NzMessageContainerComponent, NzMessageComponent], + providers: [NZ_MESSAGE_DEFAULT_CONFIG_PROVIDER, NzMessageService], + entryComponents: [NzMessageContainerComponent] }) -export class NzMessageModule { -} +export class NzMessageModule {} diff --git a/components/message/nz-message.service.ts b/components/message/nz-message.service.ts index 5ff054b08d2..b69c91fcf08 100644 --- a/components/message/nz-message.service.ts +++ b/components/message/nz-message.service.ts @@ -1,5 +1,13 @@ import { Overlay } from '@angular/cdk/overlay'; -import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector, TemplateRef, Type } from '@angular/core'; +import { + ApplicationRef, + ComponentFactoryResolver, + EmbeddedViewRef, + Injectable, + Injector, + TemplateRef, + Type +} from '@angular/core'; import { NzMessageConfig } from './nz-message-config'; import { NzMessageContainerComponent } from './nz-message-container.component'; @@ -64,7 +72,7 @@ export class NzMessageBaseService< this.appRef.attachView(componentRef.hostView); // Load view into app root const overlayPane = this.overlay.create().overlayElement; overlayPane.style.zIndex = '1010'; // Patching: assign the same zIndex of ant-message to it's parent overlay panel, to the ant-message's zindex work. - overlayPane.appendChild((componentRef.hostView as EmbeddedViewRef<{}>).rootNodes[ 0 ] as HTMLElement); + overlayPane.appendChild((componentRef.hostView as EmbeddedViewRef<{}>).rootNodes[0] as HTMLElement); return componentRef.instance; } @@ -73,14 +81,12 @@ export class NzMessageBaseService< @Injectable({ providedIn: 'root' }) -export class NzMessageService extends NzMessageBaseService { - - constructor( - overlay: Overlay, - injector: Injector, - cfr: ComponentFactoryResolver, - appRef: ApplicationRef) { - +export class NzMessageService extends NzMessageBaseService< + NzMessageContainerComponent, + NzMessageData, + NzMessageConfig +> { + constructor(overlay: Overlay, injector: Injector, cfr: ComponentFactoryResolver, appRef: ApplicationRef) { super(overlay, NzMessageContainerComponent, injector, cfr, appRef, 'message-'); } diff --git a/components/message/nz-message.spec.ts b/components/message/nz-message.spec.ts index fbaf0eb776e..831de8dda70 100644 --- a/components/message/nz-message.spec.ts +++ b/components/message/nz-message.spec.ts @@ -1,4 +1,3 @@ - import { OverlayContainer } from '@angular/cdk/overlay'; import { Component, TemplateRef, ViewChild } from '@angular/core'; import { fakeAsync, inject, tick, ComponentFixture, TestBed } from '@angular/core/testing'; @@ -19,15 +18,15 @@ describe('NzMessage', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports: [ NzMessageModule, NoopAnimationsModule ], - declarations: [ NzTestMessageBasicComponent ], - providers: [ { provide: NZ_MESSAGE_CONFIG, useValue: { nzMaxStack: 2, nzTop: 24 } } ] + imports: [NzMessageModule, NoopAnimationsModule], + declarations: [NzTestMessageBasicComponent], + providers: [{ provide: NZ_MESSAGE_CONFIG, useValue: { nzMaxStack: 2, nzTop: 24 } }] }); TestBed.compileComponents(); })); - beforeEach(inject([ NzMessageService, OverlayContainer ], (m: NzMessageService, oc: OverlayContainer) => { + beforeEach(inject([NzMessageService, OverlayContainer], (m: NzMessageService, oc: OverlayContainer) => { messageService = m; overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); @@ -42,46 +41,46 @@ describe('NzMessage', () => { testComponent = fixture.debugElement.componentInstance; }); - it('should open a message box with success', (() => { + it('should open a message box with success', () => { messageService.success('SUCCESS'); fixture.detectChanges(); expect((overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement).style.zIndex).toBe('1010'); expect(overlayContainerElement.textContent).toContain('SUCCESS'); expect(overlayContainerElement.querySelector('.anticon-check-circle')).not.toBeNull(); - })); + }); - it('should open a message box with error', (() => { + it('should open a message box with error', () => { messageService.error('ERROR'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('ERROR'); expect(overlayContainerElement.querySelector('.anticon-close-circle')).not.toBeNull(); - })); + }); - it('should open a message box with warning', (() => { + it('should open a message box with warning', () => { messageService.warning('WARNING'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('WARNING'); expect(overlayContainerElement.querySelector('.anticon-exclamation-circle')).not.toBeNull(); - })); + }); - it('should open a message box with info', (() => { + it('should open a message box with info', () => { messageService.info('INFO'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('INFO'); expect(overlayContainerElement.querySelector('.anticon-info-circle')).not.toBeNull(); - })); + }); - it('should open a message box with loading', (() => { + it('should open a message box with loading', () => { messageService.loading('LOADING'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('LOADING'); expect(overlayContainerElement.querySelector('.anticon-loading')).not.toBeNull(); - })); + }); it('should support template', fakeAsync(() => { messageService.info(testComponent.template); @@ -128,7 +127,7 @@ describe('NzMessage', () => { })); it('should keep the balance of messages length and then remove all', fakeAsync(() => { - [ 1, 2, 3 ].forEach(id => { + [1, 2, 3].forEach(id => { const content = `SUCCESS-${id}`; messageService.success(content); fixture.detectChanges(); diff --git a/components/modal/css-unit.pipe.ts b/components/modal/css-unit.pipe.ts index 88a8b1b06f4..9724d00ccc0 100644 --- a/components/modal/css-unit.pipe.ts +++ b/components/modal/css-unit.pipe.ts @@ -3,7 +3,6 @@ import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'toCssUnit' }) - export class CssUnitPipe implements PipeTransform { transform(value: number | string, defaultUnit: string = 'px'): string { const formatted = +value; // force convert diff --git a/components/modal/demo/async.ts b/components/modal/demo/async.ts index e772af1546b..3209aa83ab3 100644 --- a/components/modal/demo/async.ts +++ b/components/modal/demo/async.ts @@ -6,7 +6,13 @@ import { Component } from '@angular/core'; - +

    Modal Content

    `, diff --git a/components/modal/demo/confirm-promise.ts b/components/modal/demo/confirm-promise.ts index cee05281fa2..00139f67d35 100644 --- a/components/modal/demo/confirm-promise.ts +++ b/components/modal/demo/confirm-promise.ts @@ -6,20 +6,21 @@ import { NzModalRef, NzModalService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoModalConfirmPromiseComponent { confirmModal: NzModalRef; // For testing by now - constructor(private modal: NzModalService) { } + constructor(private modal: NzModalService) {} showConfirm(): void { this.confirmModal = this.modal.confirm({ nzTitle: 'Do you Want to delete these items?', nzContent: 'When clicked the OK button, this dialog will be closed after 1 second', - nzOnOk: () => new Promise((resolve, reject) => { - setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); - }).catch(() => console.log('Oops errors!')) + nzOnOk: () => + new Promise((resolve, reject) => { + setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); + }).catch(() => console.log('Oops errors!')) }); } } diff --git a/components/modal/demo/confirm.ts b/components/modal/demo/confirm.ts index 56536bc2260..aee248e5342 100644 --- a/components/modal/demo/confirm.ts +++ b/components/modal/demo/confirm.ts @@ -7,33 +7,34 @@ import { NzModalService } from 'ng-zorro-antd'; `, - styles : [ - `button { - margin-right: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + } + ` ] }) export class NzDemoModalConfirmComponent { - constructor(private modalService: NzModalService) { - } + constructor(private modalService: NzModalService) {} showConfirm(): void { this.modalService.confirm({ - nzTitle : 'Do you Want to delete these items?', + nzTitle: 'Do you Want to delete these items?', nzContent: 'Some descriptions', - nzOnOk : () => console.log('OK') + nzOnOk: () => console.log('OK') }); } showDeleteConfirm(): void { this.modalService.confirm({ - nzTitle : 'Are you sure delete this task?', - nzContent : 'Some descriptions', - nzOkText : 'Yes', - nzOkType : 'danger', - nzOnOk : () => console.log('OK'), + nzTitle: 'Are you sure delete this task?', + nzContent: 'Some descriptions', + nzOkText: 'Yes', + nzOkType: 'danger', + nzOnOk: () => console.log('OK'), nzCancelText: 'No', - nzOnCancel : () => console.log('Cancel') + nzOnCancel: () => console.log('Cancel') }); } } diff --git a/components/modal/demo/footer.ts b/components/modal/demo/footer.ts index 33a4f981418..8ac74362aaa 100644 --- a/components/modal/demo/footer.ts +++ b/components/modal/demo/footer.ts @@ -1,13 +1,18 @@ import { Component } from '@angular/core'; - @Component({ selector: 'nz-demo-modal-footer', template: ` - + Custom Modal Title @@ -33,7 +38,7 @@ export class NzDemoModalFooterComponent { isVisible = false; isConfirmLoading = false; - constructor() { } + constructor() {} showModal(): void { this.isVisible = true; diff --git a/components/modal/demo/info.ts b/components/modal/demo/info.ts index b468ef55b0e..9b523b409e6 100644 --- a/components/modal/demo/info.ts +++ b/components/modal/demo/info.ts @@ -9,14 +9,16 @@ import { NzModalService } from 'ng-zorro-antd'; `, - styles : [ - `button { - margin-right: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + } + ` ] }) export class NzDemoModalInfoComponent { - constructor(private modalService: NzModalService) { } + constructor(private modalService: NzModalService) {} info(): void { this.modalService.info({ diff --git a/components/modal/demo/locale.ts b/components/modal/demo/locale.ts index 311ddbbd700..58ddbd63a56 100644 --- a/components/modal/demo/locale.ts +++ b/components/modal/demo/locale.ts @@ -19,7 +19,7 @@ import { NzModalService } from 'ng-zorro-antd';

    Bla bla ...

    -
    +
    `, styles: [] @@ -27,7 +27,7 @@ import { NzModalService } from 'ng-zorro-antd'; export class NzDemoModalLocaleComponent { isVisible = false; - constructor(private modalService: NzModalService) { } + constructor(private modalService: NzModalService) {} showModal(): void { this.isVisible = true; diff --git a/components/modal/demo/manual.ts b/components/modal/demo/manual.ts index d5ff5b99863..f56fad26aef 100644 --- a/components/modal/demo/manual.ts +++ b/components/modal/demo/manual.ts @@ -9,7 +9,7 @@ import { NzModalService } from 'ng-zorro-antd'; styles: [] }) export class NzDemoModalManualComponent { - constructor(private modalService: NzModalService) { } + constructor(private modalService: NzModalService) {} success(): void { const modal = this.modalService.success({ diff --git a/components/modal/demo/position.ts b/components/modal/demo/position.ts index 4501bc3c98b..01db401760c 100644 --- a/components/modal/demo/position.ts +++ b/components/modal/demo/position.ts @@ -4,32 +4,46 @@ import { Component } from '@angular/core'; selector: 'nz-demo-modal-position', template: ` - +

    some contents...

    some contents...

    some contents...

    -

    +

    - +

    some contents...

    some contents...

    some contents...

    `, - styles: [ ` - ::ng-deep .vertical-center-modal { - display: flex; - align-items: center; - justify-content: center; - } - - ::ng-deep .vertical-center-modal .ant-modal { - top: 0; - } - ` ] + styles: [ + ` + ::ng-deep .vertical-center-modal { + display: flex; + align-items: center; + justify-content: center; + } + + ::ng-deep .vertical-center-modal .ant-modal { + top: 0; + } + ` + ] }) export class NzDemoModalPositionComponent { isVisibleTop = false; diff --git a/components/modal/demo/service.ts b/components/modal/demo/service.ts index 6dbcfaa03b4..e5f76c5baa3 100644 --- a/components/modal/demo/service.ts +++ b/components/modal/demo/service.ts @@ -24,7 +24,9 @@ import { NzModalRef, NzModalService } from 'ng-zorro-antd';

    some contents...

    - +

    @@ -38,12 +40,16 @@ import { NzModalRef, NzModalService } from 'ng-zorro-antd';

    - This is a non-service html modal + This is a non-service html modal `, - styles : [ - `button { - margin-right: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + } + ` ] }) export class NzDemoModalServiceComponent { @@ -52,14 +58,14 @@ export class NzDemoModalServiceComponent { htmlModalVisible = false; disabled = false; - constructor(private modalService: NzModalService) { } + constructor(private modalService: NzModalService) {} createModal(): void { this.modalService.create({ nzTitle: 'Modal Title', nzContent: 'string, will close after 1 sec', nzClosable: false, - nzOnOk: () => new Promise((resolve) => setTimeout(resolve, 1000)) + nzOnOk: () => new Promise(resolve => setTimeout(resolve, 1000)) }); } @@ -90,18 +96,20 @@ export class NzDemoModalServiceComponent { title: 'title in component', subtitle: 'component sub title,will be changed after 2 sec' }, - nzFooter: [{ - label: 'change component tilte from outside', - onClick: (componentInstance) => { - componentInstance!.title = 'title in inner component is changed'; + nzFooter: [ + { + label: 'change component tilte from outside', + onClick: componentInstance => { + componentInstance!.title = 'title in inner component is changed'; + } } - }] + ] }); modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!')); // Return a result when closed - modal.afterClose.subscribe((result) => console.log('[afterClose] The result is:', result)); + modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result)); // delay until modal instance created setTimeout(() => { @@ -123,7 +131,8 @@ export class NzDemoModalServiceComponent { { label: 'Confirm', type: 'primary', - onClick: () => this.modalService.confirm({ nzTitle: 'Confirm Modal Title', nzContent: 'Confirm Modal Content' }) + onClick: () => + this.modalService.confirm({ nzTitle: 'Confirm Modal Title', nzContent: 'Confirm Modal Content' }) }, { label: 'Change Button Status', @@ -131,7 +140,7 @@ export class NzDemoModalServiceComponent { loading: false, onClick(): void { this.loading = true; - setTimeout(() => this.loading = false, 1000); + setTimeout(() => (this.loading = false), 1000); setTimeout(() => { this.loading = false; this.disabled = true; @@ -151,13 +160,15 @@ export class NzDemoModalServiceComponent { openAndCloseAll(): void { let pos = 0; - // @ts-ignore - [ 'create', 'info', 'success', 'error' ].forEach((method) => this.modalService[method]({ - nzMask: false, - nzTitle: `Test ${method} title`, - nzContent: `Test content: ${method}`, - nzStyle: { position: 'absolute', top: `${pos * 70}px`, left: `${(pos++) * 300}px` } - })); + ['create', 'info', 'success', 'error'].forEach(method => + // @ts-ignore + this.modalService[method]({ + nzMask: false, + nzTitle: `Test ${method} title`, + nzContent: `Test content: ${method}`, + nzStyle: { position: 'absolute', top: `${pos * 70}px`, left: `${pos++ * 300}px` } + }) + ); this.htmlModalVisible = true; @@ -184,7 +195,7 @@ export class NzModalCustomComponent { @Input() title: string; @Input() subtitle: string; - constructor(private modal: NzModalRef) { } + constructor(private modal: NzModalRef) {} destroyModal(): void { this.modal.destroy({ data: 'this the result data' }); diff --git a/components/modal/nz-modal-control.service.ts b/components/modal/nz-modal-control.service.ts index 806588efa09..b45eda69275 100644 --- a/components/modal/nz-modal-control.service.ts +++ b/components/modal/nz-modal-control.service.ts @@ -25,7 +25,8 @@ export class NzModalControlService { private rootAfterAllClose: Subject | null = this.parentService ? null : new Subject(); private rootRegisteredMetaMap: Map | null = this.parentService ? null : new Map(); - private get registeredMetaMap(): Map { // Registered modal for later usage + private get registeredMetaMap(): Map { + // Registered modal for later usage return this.parentService ? this.parentService.registeredMetaMap : this.rootRegisteredMetaMap!; } @@ -62,7 +63,7 @@ export class NzModalControlService { let i = this.openModals.length; while (i--) { - this.openModals[ i ].close(); + this.openModals[i].close(); } } diff --git a/components/modal/nz-modal-ref.class.ts b/components/modal/nz-modal-ref.class.ts index 2825c36bb34..7ed32297a42 100644 --- a/components/modal/nz-modal-ref.class.ts +++ b/components/modal/nz-modal-ref.class.ts @@ -6,7 +6,8 @@ import { NzModalComponent } from './nz-modal.component'; * API class that public to users to handle the modal instance. * NzModalRef is aim to avoid accessing to the modal instance directly by users. */ -export abstract class NzModalRef { // tslint:disable-line:no-any +// tslint:disable-next-line:no-any +export abstract class NzModalRef { abstract afterOpen: Observable; abstract afterClose: Observable; diff --git a/components/modal/nz-modal.component.ts b/components/modal/nz-modal.component.ts index 586258c02ce..dd86b721078 100644 --- a/components/modal/nz-modal.component.ts +++ b/components/modal/nz-modal.component.ts @@ -43,15 +43,15 @@ export const MODAL_ANIMATE_DURATION = 200; // Duration when perform animations ( type AnimationState = 'enter' | 'leave' | null; @Component({ - selector : 'nz-modal', - templateUrl : './nz-modal.component.html', + selector: 'nz-modal', + templateUrl: './nz-modal.component.html', // Using OnPush for modal caused footer can not to detect changes. we can fix it when 8.x. changeDetection: ChangeDetectionStrategy.Default }) // tslint:disable-next-line:no-any -export class NzModalComponent extends NzModalRef implements OnInit, OnChanges, AfterViewInit, OnDestroy, ModalOptions { - +export class NzModalComponent extends NzModalRef + implements OnInit, OnChanges, AfterViewInit, OnDestroy, ModalOptions { @Input() @InputBoolean() nzVisible: boolean = false; @Input() @InputBoolean() nzClosable: boolean = true; @Input() @InputBoolean() nzMask: boolean = true; @@ -91,11 +91,13 @@ export class NzModalComponent extends NzModalRef impleme @ViewChild('bodyContainer', { read: ViewContainerRef }) bodyContainer: ViewContainerRef; @ViewChild('autoFocusButtonOk', { read: ElementRef }) autoFocusButtonOk: ElementRef; // Only aim to focus the ok button that needs to be auto focused - get afterOpen(): Observable { // Observable alias for nzAfterOpen + get afterOpen(): Observable { + // Observable alias for nzAfterOpen return this.nzAfterOpen.asObservable(); } - get afterClose(): Observable { // Observable alias for nzAfterClose + get afterClose(): Observable { + // Observable alias for nzAfterClose return this.nzAfterClose.asObservable(); } @@ -111,7 +113,7 @@ export class NzModalComponent extends NzModalRef impleme return !this.nzVisible && !this.animationState; } // Indicate whether this dialog should hidden - locale: { okText?: string, cancelText?: string } = {}; + locale: { okText?: string; cancelText?: string } = {}; maskAnimationClassMap: object | null; modalAnimationClassMap: object | null; transformOrigin = '0px 0px 0px'; // The origin point that animation based on @@ -124,7 +126,7 @@ export class NzModalComponent extends NzModalRef impleme private focusTrap: FocusTrap; private scrollStrategy: BlockScrollStrategy; - [ key: string ]: any // tslint:disable-line:no-any + [key: string]: any; // tslint:disable-line:no-any constructor( private overlay: Overlay, @@ -145,16 +147,19 @@ export class NzModalComponent extends NzModalRef impleme ngOnInit(): void { this.i18n.localeChange.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { - this.locale = this.i18n.getLocaleData('Modal') as { okText: string, cancelText: string }; + this.locale = this.i18n.getLocaleData('Modal') as { okText: string; cancelText: string }; }); - fromEvent(this.document.body, 'keydown').pipe(takeUntil(this.unsubscribe$)).subscribe(e => this.keydownListener(e)); + fromEvent(this.document.body, 'keydown') + .pipe(takeUntil(this.unsubscribe$)) + .subscribe(e => this.keydownListener(e)); if (this.isComponent(this.nzContent)) { this.createDynamicComponent(this.nzContent as Type); // Create component along without View } - if (this.isModalButtons(this.nzFooter)) { // Setup default button options + if (this.isModalButtons(this.nzFooter)) { + // Setup default button options this.nzFooter = this.formatModalButtons(this.nzFooter as Array>); } @@ -162,7 +167,8 @@ export class NzModalComponent extends NzModalRef impleme this.container = typeof this.nzGetContainer === 'function' ? this.nzGetContainer() : this.nzGetContainer; if (this.container instanceof HTMLElement) { this.container.appendChild(this.elementRef.nativeElement); - } else if (this.container instanceof OverlayRef) { // NOTE: only attach the dom to overlay, the view container is not changed actually + } else if (this.container instanceof OverlayRef) { + // NOTE: only attach the dom to overlay, the view container is not changed actually this.container.overlayElement.appendChild(this.elementRef.nativeElement); } @@ -219,7 +225,8 @@ export class NzModalComponent extends NzModalRef impleme this.changeVisibleFromInside(false, result); } - destroy(result?: R): void { // Destroy equals Close + destroy(result?: R): void { + // Destroy equals Close this.close(result); } @@ -269,17 +276,17 @@ export class NzModalComponent extends NzModalRef impleme } public onClickOkCancel(type: 'ok' | 'cancel'): void { - const trigger = { 'ok': this.nzOnOk, 'cancel': this.nzOnCancel }[ type ]; - const loadingKey = { 'ok': 'nzOkLoading', 'cancel': 'nzCancelLoading' }[ type ]; + const trigger = { ok: this.nzOnOk, cancel: this.nzOnCancel }[type]; + const loadingKey = { ok: 'nzOkLoading', cancel: 'nzCancelLoading' }[type]; if (trigger instanceof EventEmitter) { trigger.emit(this.getContentComponent()); } else if (typeof trigger === 'function') { const result = trigger(this.getContentComponent()); - const caseClose = (doClose: boolean | void | {}) => (doClose !== false) && this.close(doClose as R); // Users can return "false" to prevent closing by default + const caseClose = (doClose: boolean | void | {}) => doClose !== false && this.close(doClose as R); // Users can return "false" to prevent closing by default if (isPromise(result)) { - this[ loadingKey ] = true; + this[loadingKey] = true; const handleThen = (doClose: boolean | void | {}) => { - this[ loadingKey ] = false; + this[loadingKey] = false; caseClose(doClose); }; (result as Promise).then(handleThen).catch(handleThen); @@ -307,30 +314,30 @@ export class NzModalComponent extends NzModalRef impleme // Do rest things when visible state changed private handleVisibleStateChange(visible: boolean, animation: boolean = true, closeResult?: R): Promise { - if (visible) { // Hide scrollbar at the first time when shown up + if (visible) { + // Hide scrollbar at the first time when shown up this.scrollStrategy.enable(); this.savePreviouslyFocusedElement(); this.trapFocus(); } - return Promise - .resolve(animation ? this.animateTo(visible) : undefined) - .then(() => { // Emit open/close event after animations over - if (visible) { - this.nzAfterOpen.emit(); - } else { - this.nzAfterClose.emit(closeResult); - this.restoreFocus(); - this.scrollStrategy.disable(); - // Mark the for check so it can react if the view container is using OnPush change detection. - this.cdr.markForCheck(); - } - }); + return Promise.resolve(animation ? this.animateTo(visible) : undefined).then(() => { + // Emit open/close event after animations over + if (visible) { + this.nzAfterOpen.emit(); + } else { + this.nzAfterClose.emit(closeResult); + this.restoreFocus(); + this.scrollStrategy.disable(); + // Mark the for check so it can react if the view container is using OnPush change detection. + this.cdr.markForCheck(); + } + }); } // Lookup a button's property, if the prop is a function, call & then return the result, otherwise, return itself. public getButtonCallableProp(options: ModalButtonOptions, prop: string): {} { - const value = options[ prop ]; + const value = options[prop]; const args: T[] = []; if (this.contentComponentRef) { args.push(this.contentComponentRef.instance); @@ -343,7 +350,7 @@ export class NzModalComponent extends NzModalRef impleme const result = this.getButtonCallableProp(button, 'onClick'); // Call onClick directly if (isPromise(result)) { button.loading = true; - (result as Promise<{}>).then(() => button.loading = false).catch(() => button.loading = false); + (result as Promise<{}>).then(() => (button.loading = false)).catch(() => (button.loading = false)); } } @@ -362,12 +369,12 @@ export class NzModalComponent extends NzModalRef impleme this.animationState = state; if (state) { this.maskAnimationClassMap = { - [ `fade-${state}` ] : true, - [ `fade-${state}-active` ]: true + [`fade-${state}`]: true, + [`fade-${state}-active`]: true }; this.modalAnimationClassMap = { - [ `zoom-${state}` ] : true, - [ `zoom-${state}-active` ]: true + [`zoom-${state}`]: true, + [`zoom-${state}-active`]: true }; } else { this.maskAnimationClassMap = this.modalAnimationClassMap = null; @@ -375,27 +382,34 @@ export class NzModalComponent extends NzModalRef impleme } private animateTo(isVisible: boolean): Promise { - if (isVisible) { // Figure out the lastest click position when shows up + if (isVisible) { + // Figure out the lastest click position when shows up setTimeout(() => this.updateTransformOrigin()); // [NOTE] Using timeout due to the document.click event is fired later than visible change, so if not postponed to next event-loop, we can't get the lastest click position } this.changeAnimationState(isVisible ? 'enter' : 'leave'); - return new Promise((resolve) => setTimeout(() => { // Return when animation is over - this.changeAnimationState(null); - resolve(); - }, this.nzNoAnimation ? 0 : MODAL_ANIMATE_DURATION)); + return new Promise(resolve => + setTimeout( + () => { + // Return when animation is over + this.changeAnimationState(null); + resolve(); + }, + this.nzNoAnimation ? 0 : MODAL_ANIMATE_DURATION + ) + ); } private formatModalButtons(buttons: Array>): Array> { - return buttons.map((button) => { + return buttons.map(button => { return { ...{ - type : 'default', - size : 'default', + type: 'default', + size: 'default', autoLoading: true, - show : true, - loading : false, - disabled : false + show: true, + loading: false, + disabled: false }, ...button }; @@ -409,8 +423,8 @@ export class NzModalComponent extends NzModalRef impleme private createDynamicComponent(component: Type): void { const factory = this.cfr.resolveComponentFactory(component); const childInjector = Injector.create({ - providers: [ { provide: NzModalRef, useValue: this } ], - parent : this.viewContainer.parentInjector + providers: [{ provide: NzModalRef, useValue: this }], + parent: this.viewContainer.parentInjector }); this.contentComponentRef = factory.create(childInjector); if (this.nzComponentParams) { @@ -425,7 +439,8 @@ export class NzModalComponent extends NzModalRef impleme const modalElement = this.modalContainer.nativeElement as HTMLElement; const lastPosition = ModalUtil.getLastClickPosition(); if (lastPosition) { - this.transformOrigin = `${lastPosition.x - modalElement.offsetLeft}px ${lastPosition.y - modalElement.offsetTop}px 0px`; + this.transformOrigin = `${lastPosition.x - modalElement.offsetLeft}px ${lastPosition.y - + modalElement.offsetTop}px 0px`; } } diff --git a/components/modal/nz-modal.module.ts b/components/modal/nz-modal.module.ts index 2221f6aa0ac..8f0030edb0a 100644 --- a/components/modal/nz-modal.module.ts +++ b/components/modal/nz-modal.module.ts @@ -14,11 +14,10 @@ import { NzModalComponent } from './nz-modal.component'; import { NzModalService } from './nz-modal.service'; @NgModule({ - imports : [ CommonModule, OverlayModule, NzI18nModule, NzButtonModule, LoggerModule, NzIconModule, NzNoAnimationModule ], - exports : [ NzModalComponent ], - declarations : [ NzModalComponent, CssUnitPipe ], - entryComponents: [ NzModalComponent ], - providers : [ NzModalControlService, NzModalService ] + imports: [CommonModule, OverlayModule, NzI18nModule, NzButtonModule, LoggerModule, NzIconModule, NzNoAnimationModule], + exports: [NzModalComponent], + declarations: [NzModalComponent, CssUnitPipe], + entryComponents: [NzModalComponent], + providers: [NzModalControlService, NzModalService] }) -export class NzModalModule { -} +export class NzModalModule {} diff --git a/components/modal/nz-modal.service.ts b/components/modal/nz-modal.service.ts index 22c8bc3d3e5..3f3896fd90c 100644 --- a/components/modal/nz-modal.service.ts +++ b/components/modal/nz-modal.service.ts @@ -19,7 +19,8 @@ export class ModalBuilderForService { constructor(private overlay: Overlay, options: ModalOptionsForService = {}) { this.createModal(); - if (!('nzGetContainer' in options)) { // As we use CDK to create modal in service by force, there is no need to use nzGetContainer + if (!('nzGetContainer' in options)) { + // As we use CDK to create modal in service by force, there is no need to use nzGetContainer options.nzGetContainer = undefined; // Override nzGetContainer's default value to prevent creating another overlay } @@ -63,11 +64,7 @@ export class NzModalService { return this.modalControl.afterAllClose.asObservable(); } - constructor( - private overlay: Overlay, - private logger: LoggerService, - private modalControl: NzModalControlService) { - } + constructor(private overlay: Overlay, private logger: LoggerService, private modalControl: NzModalControlService) {} // Closes all of the currently-open dialogs closeAll(): void { @@ -76,8 +73,7 @@ export class NzModalService { create(options: ModalOptionsForService = {}): NzModalRef { if (typeof options.nzOnCancel !== 'function') { - options.nzOnCancel = () => { - }; // Leave a empty function to close this modal by default + options.nzOnCancel = () => {}; // Leave a empty function to close this modal by default } // NOTE: use NzModalComponent as the NzModalRef by now, we may need archive the real NzModalRef object in the future @@ -93,9 +89,9 @@ export class NzModalService { if (!('nzWidth' in options)) { options.nzWidth = 416; } - if (typeof options.nzOnOk !== 'function') { // NOTE: only support function currently by calling confirm() - options.nzOnOk = () => { - }; // Leave a empty function to close this modal by default + if (typeof options.nzOnOk !== 'function') { + // NOTE: only support function currently by calling confirm() + options.nzOnOk = () => {}; // Leave a empty function to close this modal by default } options.nzModalType = 'confirm'; @@ -122,15 +118,16 @@ export class NzModalService { private simpleConfirm(options: ModalOptionsForService = {}, confirmType: ConfirmType): NzModalRef { const iconMap: IndexableObject = { - 'info' : 'info-circle', - 'success': 'check-circle', - 'error' : 'close-circle', - 'warning': 'exclamation-circle' + info: 'info-circle', + success: 'check-circle', + error: 'close-circle', + warning: 'exclamation-circle' }; if (!('nzIconType' in options)) { - options.nzIconType = iconMap[ confirmType ]; + options.nzIconType = iconMap[confirmType]; } - if (!('nzCancelText' in options)) { // Remove the Cancel button if the user not specify a Cancel button + if (!('nzCancelText' in options)) { + // Remove the Cancel button if the user not specify a Cancel button options.nzCancelText = null; } return this.confirm(options, confirmType); diff --git a/components/modal/nz-modal.spec.ts b/components/modal/nz-modal.spec.ts index 0e6cedb9603..ffbb10e5707 100644 --- a/components/modal/nz-modal.spec.ts +++ b/components/modal/nz-modal.spec.ts @@ -33,9 +33,9 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzButtonModule, NzModalModule ], - declarations: [ NzDemoModalAsyncComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzButtonModule, NzModalModule], + declarations: [NzDemoModalAsyncComponent], + providers: [NzMeasureScrollbarService] }).compileComponents(); })); @@ -73,9 +73,9 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzButtonModule, NzModalModule ], - declarations: [ NzDemoModalConfirmPromiseComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzButtonModule, NzModalModule], + declarations: [NzDemoModalConfirmPromiseComponent], + providers: [NzMeasureScrollbarService] }).compileComponents(); })); @@ -123,9 +123,9 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzModalModule, NzIconTestModule ], - declarations: [ TestBasicServiceComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzModalModule, NzIconTestModule], + declarations: [TestBasicServiceComponent], + providers: [NzMeasureScrollbarService] }).compileComponents(); })); @@ -147,13 +147,21 @@ describe('modal testing (legacy)', () => { expect(modalInstance.changeVisibleFromInside(true) instanceof Promise).toBe(true); expect((modalElement.querySelector('.ant-modal-wrap') as HTMLElement).style.zIndex).toBe('1888'); - expect((modalElement.querySelector('.ant-modal-wrap') as HTMLElement).classList.contains('test-wrap-class-name')).toBe(true); + expect( + (modalElement.querySelector('.ant-modal-wrap') as HTMLElement).classList.contains('test-wrap-class-name') + ).toBe(true); expect((modalElement.querySelector('.ant-modal') as HTMLElement).style.width).toBe('250px'); - expect((modalElement.querySelector('.ant-modal') as HTMLElement).classList.contains('test-class-name')).toBe(true); + expect((modalElement.querySelector('.ant-modal') as HTMLElement).classList.contains('test-class-name')).toBe( + true + ); expect((modalElement.querySelector('.ant-modal') as HTMLElement).style.top).toBe('20pt'); - expect((modalElement.querySelector('.ant-modal-title') as HTMLElement).innerHTML.indexOf('TEST BOLD TITLE')).toBeGreaterThan(-1); + expect( + (modalElement.querySelector('.ant-modal-title') as HTMLElement).innerHTML.indexOf('TEST BOLD TITLE') + ).toBeGreaterThan(-1); // expect((modalElement.querySelector('.ant-modal-footer') as HTMLElement).innerHTML.indexOf('
    custom html footer: OK
    ')).toBeGreaterThan(-1); - expect((modalElement.querySelector('.ant-modal-body') as HTMLElement).innerHTML.indexOf('

    test html content

    ')).toBeGreaterThan(-1); + expect( + (modalElement.querySelector('.ant-modal-body') as HTMLElement).innerHTML.indexOf('

    test html content

    ') + ).toBeGreaterThan(-1); expect((modalElement.querySelector('.ant-modal-body') as HTMLElement).style.background).toBe('gray'); expect(getButtonOk(modalElement).innerHTML.indexOf('custom ok')).toBeGreaterThan(-1); expect(getButtonOk(modalElement).classList.contains('ant-btn-success')).toBe(true); @@ -218,12 +226,12 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzModalModule ], - declarations: [ TestVaryServiceComponent, TestVaryServiceCustomComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzModalModule], + declarations: [TestVaryServiceComponent, TestVaryServiceCustomComponent], + providers: [NzMeasureScrollbarService] }); TestBed.overrideModule(BrowserDynamicTestingModule, { - set: { entryComponents: [ TestVaryServiceCustomComponent ] } + set: { entryComponents: [TestVaryServiceCustomComponent] } }).compileComponents(); })); @@ -270,9 +278,9 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzModalModule ], - declarations: [ TestConfirmModalComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzModalModule], + declarations: [TestConfirmModalComponent], + providers: [NzMeasureScrollbarService] }).compileComponents(); })); @@ -316,8 +324,8 @@ describe('modal testing (legacy)', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule ], - declarations: [ CssUnitPipe, TestCssUnitPipeComponent ] + imports: [NoopAnimationsModule], + declarations: [CssUnitPipe, TestCssUnitPipeComponent] }).compileComponents(); })); @@ -343,9 +351,9 @@ describe('modal testing (legacy)', () => { let fixture: ComponentFixture; const injector = TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzButtonModule, NzModalModule ], - declarations: [ NzDemoModalAsyncComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NoopAnimationsModule, NzButtonModule, NzModalModule], + declarations: [NzDemoModalAsyncComponent], + providers: [NzMeasureScrollbarService] }); fixture = TestBed.createComponent(NzDemoModalAsyncComponent); const comp = fixture.componentInstance as NzDemoModalAsyncComponent; @@ -353,9 +361,11 @@ describe('modal testing (legacy)', () => { fixture.detectChanges(); injector.get(NzI18nService).setLocale(en_US); fixture.detectChanges(); - const cancelText = (fixture.debugElement.query(By.css('nz-modal .ant-btn')).nativeElement as HTMLElement).textContent!.trim(); + const cancelText = (fixture.debugElement.query(By.css('nz-modal .ant-btn')) + .nativeElement as HTMLElement).textContent!.trim(); expect(cancelText).toBe(en_US.Modal.cancelText); - const okText = (fixture.debugElement.query(By.css('nz-modal .ant-btn-primary')).nativeElement as HTMLElement).textContent!.trim(); + const okText = (fixture.debugElement.query(By.css('nz-modal .ant-btn-primary')) + .nativeElement as HTMLElement).textContent!.trim(); expect(okText).toBe(en_US.Modal.okText); }); }); @@ -367,18 +377,15 @@ describe('NzModal', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzModalModule ], - providers : [ NzMeasureScrollbarService ], - declarations: [ - NzDemoModalBasicComponent, - ModalByServiceComponent - ] + imports: [NoopAnimationsModule, NzModalModule], + providers: [NzMeasureScrollbarService], + declarations: [NzDemoModalBasicComponent, ModalByServiceComponent] }); TestBed.compileComponents(); })); - beforeEach(inject([ NzModalService, OverlayContainer ], (ms: NzModalService, oc: OverlayContainer) => { + beforeEach(inject([NzModalService, OverlayContainer], (ms: NzModalService, oc: OverlayContainer) => { modalService = ms; overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); @@ -413,7 +420,8 @@ describe('NzModal', () => { beforeEach(() => { fixture = TestBed.createComponent(ModalByServiceComponent); }); - afterEach(fakeAsync(() => { // wait all openModals tobe closed to clean up the ModalManager as it is globally static + afterEach(fakeAsync(() => { + // wait all openModals tobe closed to clean up the ModalManager as it is globally static document.documentElement!.classList.remove('cdk-global-scrollblock'); modalService.closeAll(); fixture.detectChanges(); @@ -486,19 +494,22 @@ describe('NzModal', () => { it('should close all opened modals (include non-service modals)', fakeAsync(() => { const spy = jasmine.createSpy('afterAllClose spy'); - const modalMethods = [ 'create', 'info', 'success', 'error', 'confirm' ]; + const modalMethods = ['create', 'info', 'success', 'error', 'confirm']; const uniqueId = (name: string) => `__${name}_ID_SUFFIX__`; - const queryOverlayElement = (name: string) => overlayContainerElement.querySelector(`.${uniqueId(name)}`) as HTMLElement; + const queryOverlayElement = (name: string) => + overlayContainerElement.querySelector(`.${uniqueId(name)}`) as HTMLElement; modalService.afterAllClose.subscribe(spy); fixture.componentInstance.nonServiceModalVisible = true; // Show non-service modal // @ts-ignore - modalMethods.forEach(method => modalService[ method ]({ nzWrapClassName: uniqueId(method) })); // Service modals + modalMethods.forEach(method => modalService[method]({ nzWrapClassName: uniqueId(method) })); // Service modals fixture.detectChanges(); tick(600); - (modalMethods.concat('NON_SERVICE')).forEach(method => expect(queryOverlayElement(method).style.display).not.toBe('none')); // Cover non-service modal for later checking + modalMethods + .concat('NON_SERVICE') + .forEach(method => expect(queryOverlayElement(method).style.display).not.toBe('none')); // Cover non-service modal for later checking expect(modalService.openModals.length).toBe(6); modalService.closeAll(); @@ -510,13 +521,16 @@ describe('NzModal', () => { })); it('should only a confirm button when the type is "info"|"success"|"error"|"warning"', fakeAsync(() => { - const modalMethods = [ 'info', 'success', 'error', 'warning' ]; + const modalMethods = ['info', 'success', 'error', 'warning']; const uniqueId = (name: string) => `__${name}_ID_SUFFIX__`; - const queryOverlayElement = (name: string) => overlayContainerElement.querySelectorAll(`.${uniqueId(name)} .ant-modal-confirm-btns > button`) as NodeListOf; + const queryOverlayElement = (name: string) => + overlayContainerElement.querySelectorAll(`.${uniqueId(name)} .ant-modal-confirm-btns > button`) as NodeListOf< + HTMLButtonElement + >; fixture.componentInstance.nonServiceModalVisible = false; // Show non-service modal // @ts-ignore - modalMethods.forEach(method => modalService[ method ]({ nzWrapClassName: uniqueId(method) })); // Service modals + modalMethods.forEach(method => modalService[method]({ nzWrapClassName: uniqueId(method) })); // Service modals fixture.detectChanges(); tick(600); @@ -562,7 +576,7 @@ describe('NzModal', () => { const spyOk = jasmine.createSpy('ok spy'); const spyCancel = jasmine.createSpy('cancel spy'); const modalRef: NzModalRef = modalService.create({ - nzOnOk : spyOk, + nzOnOk: spyOk, nzOnCancel: spyCancel }); @@ -619,12 +633,17 @@ class NzDemoModalBasicComponent { - +

    content

    `, - styles : [] + styles: [] }) class NzDemoModalAsyncComponent { isVisible = false; @@ -652,21 +671,21 @@ class NzDemoModalAsyncComponent { template: ` `, - styles : [] + styles: [] }) class NzDemoModalConfirmPromiseComponent { confirmModal: NzModalRef; // For testing by now - constructor(private modal: NzModalService) { - } + constructor(private modal: NzModalService) {} showConfirm(): void { this.confirmModal = this.modal.confirm({ - nzTitle : 'Do you Want to delete these items?', + nzTitle: 'Do you Want to delete these items?', nzContent: 'When clicked the OK button, this dialog will be closed after 1 second', - nzOnOk : () => new Promise((resolve, reject) => { - setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); - }).catch(() => console.log('Oops errors!')) + nzOnOk: () => + new Promise((resolve, reject) => { + setTimeout(Math.random() > 0.5 ? resolve : reject, 1000); + }).catch(() => console.log('Oops errors!')) }); } } @@ -682,33 +701,33 @@ class TestBasicServiceComponent { // Testing for creating modal immediately this.basicModal = this.modalService.create({ - nzGetContainer : () => document.body, - nzZIndex : 1888, - nzWidth : 250, - nzWrapClassName : 'test-wrap-class-name', - nzClassName : 'test-class-name', - nzStyle : { left: '10px', top: '20pt', border: '2px solid red' }, - nzTitle : 'TEST BOLD TITLE', - nzContent : '

    test html content

    ', - nzClosable : false, - nzKeyboard : false, - nzMask : false, - nzMaskClosable : false, - nzMaskStyle : { opacity: 0.4 }, - nzBodyStyle : { background: 'gray' }, + nzGetContainer: () => document.body, + nzZIndex: 1888, + nzWidth: 250, + nzWrapClassName: 'test-wrap-class-name', + nzClassName: 'test-class-name', + nzStyle: { left: '10px', top: '20pt', border: '2px solid red' }, + nzTitle: 'TEST BOLD TITLE', + nzContent: '

    test html content

    ', + nzClosable: false, + nzKeyboard: false, + nzMask: false, + nzMaskClosable: false, + nzMaskStyle: { opacity: 0.4 }, + nzBodyStyle: { background: 'gray' }, // nzFooter: '
    custom html footer: OK
    ', - nzOkText : 'custom ok', - nzOkType : 'success', - nzOkLoading : false, - nzOkDisabled : false, + nzOkText: 'custom ok', + nzOkType: 'success', + nzOkLoading: false, + nzOkDisabled: false, nzCancelDisabled: false, - nzOnOk : () => { + nzOnOk: () => { console.log('click ok'); return false; }, - nzCancelText : 'custom cancel', - nzCancelLoading : true, - nzOnCancel : () => console.log('click cancel') + nzCancelText: 'custom cancel', + nzCancelLoading: true, + nzOnCancel: () => console.log('click cancel') }); } } @@ -717,23 +736,22 @@ class TestBasicServiceComponent { template: `` }) class TestVaryServiceComponent { - constructor(private modalService: NzModalService) { - } + constructor(private modalService: NzModalService) {} createWithVary(): NzModalRef { const modal = this.modalService.create({ - nzContent : TestVaryServiceCustomComponent, + nzContent: TestVaryServiceCustomComponent, nzComponentParams: { title: 'internal title', subtitle: 'subtitle' }, - nzFooter : [ + nzFooter: [ { - label : 'change title from outside', - onClick: (componentInstance) => { + label: 'change title from outside', + onClick: componentInstance => { componentInstance!.title = 'internal title changed'; return Promise.resolve(); } }, { - label : 'show loading', + label: 'show loading', onClick: () => Promise.reject(null) } ] @@ -745,7 +763,8 @@ class TestVaryServiceComponent { @Component({ template: ` -

    {{ title }}

    {{ subtitle }}

    +

    {{ title }}

    +

    {{ subtitle }}

    ` }) @@ -753,8 +772,7 @@ export class TestVaryServiceCustomComponent { @Input() title: string; @Input() subtitle: string; - constructor(private modal: NzModalRef, public elementRef: ElementRef) { - } + constructor(private modal: NzModalRef, public elementRef: ElementRef) {} destroyModal(): void { this.modal.destroy(); @@ -765,8 +783,7 @@ export class TestVaryServiceCustomComponent { template: `` }) export class TestConfirmModalComponent { - constructor(public modalService: NzModalService) { - } + constructor(public modalService: NzModalService) {} createConfirm(): NzModalRef { this.modalService.confirm(); // [Testing Required] Only for coverage temporarily @@ -780,12 +797,12 @@ export class TestConfirmModalComponent { } createOtherModals(): string[] { - return [ 'info', 'success', 'error', 'warning' ].map(type => { + return ['info', 'success', 'error', 'warning'].map(type => { const modalId = generateUniqueId(); // @ts-ignore - this.modalService[ type ]({ nzClassName: modalId }); + this.modalService[type]({ nzClassName: modalId }); // @ts-ignore - this.modalService[ type ](); // [Testing Required] Only for coverage temporarily + this.modalService[type](); // [Testing Required] Only for coverage temporarily return modalId; }); } @@ -793,17 +810,17 @@ export class TestConfirmModalComponent { @Component({ template: ` -
    ` +
    + ` }) -class TestCssUnitPipeComponent { -} +class TestCssUnitPipeComponent {} @Component({ - selector : 'nz-modal-by-service', - template : ` + selector: 'nz-modal-by-service', + template: ` `, - providers: [ NzModalControlService ] // Testing for service with parent service + providers: [NzModalControlService] // Testing for service with parent service }) export class ModalByServiceComponent { nonServiceModalVisible = false; @@ -837,14 +854,19 @@ function generateUniqueId(): string { } function getButtonOk(modalElement: HTMLElement): HTMLButtonElement { - return isConfirmModal(modalElement) ? modalElement.querySelector('.ant-modal-confirm-btns button:last-child') as HTMLButtonElement : modalElement.querySelector('.ant-modal-footer button:last-child') as HTMLButtonElement; + return isConfirmModal(modalElement) + ? (modalElement.querySelector('.ant-modal-confirm-btns button:last-child') as HTMLButtonElement) + : (modalElement.querySelector('.ant-modal-footer button:last-child') as HTMLButtonElement); } function getButtonCancel(modalElement: HTMLElement): HTMLButtonElement { - return isConfirmModal(modalElement) ? modalElement.querySelector('.ant-modal-confirm-btns button:first-child') as HTMLButtonElement : modalElement.querySelector('.ant-modal-footer button:first-child') as HTMLButtonElement; + return isConfirmModal(modalElement) + ? (modalElement.querySelector('.ant-modal-confirm-btns button:first-child') as HTMLButtonElement) + : (modalElement.querySelector('.ant-modal-footer button:first-child') as HTMLButtonElement); } -function getButtonClose(modalElement: HTMLElement): HTMLButtonElement { // For normal modal only +function getButtonClose(modalElement: HTMLElement): HTMLButtonElement { + // For normal modal only return modalElement.querySelector('.ant-modal-close') as HTMLButtonElement; } diff --git a/components/modal/nz-modal.type.ts b/components/modal/nz-modal.type.ts index 6a51d18e2f9..9c6fc9c8b7d 100644 --- a/components/modal/nz-modal.type.ts +++ b/components/modal/nz-modal.type.ts @@ -1,14 +1,15 @@ import { OverlayRef } from '@angular/cdk/overlay'; import { EventEmitter, TemplateRef, Type } from '@angular/core'; -export type OnClickCallback = ((instance: T) => (false | void | {}) | Promise); +export type OnClickCallback = (instance: T) => (false | void | {}) | Promise; export type ModalType = 'default' | 'confirm'; // Different modal styles we have supported export type ConfirmType = 'confirm' | 'info' | 'success' | 'error' | 'warning'; // Subtypes of Confirm Modal // Public options for using by service -export interface ModalOptions { // tslint:disable-line:no-any +// tslint:disable-next-line:no-any +export interface ModalOptions { nzModalType?: ModalType; nzVisible?: boolean; nzZIndex?: number; @@ -45,12 +46,14 @@ export interface ModalOptions { // tslint:disable-line:no-any } // tslint:disable-next-line:no-any -export interface ModalOptionsForService extends ModalOptions { // Limitations for using by service +export interface ModalOptionsForService extends ModalOptions { + // Limitations for using by service nzOnOk?: OnClickCallback; nzOnCancel?: OnClickCallback; } -export interface ModalButtonOptions { // tslint:disable-line:no-any +// tslint:disable-next-line:no-any +export interface ModalButtonOptions { label: string; type?: string; shape?: string; @@ -62,8 +65,8 @@ export interface ModalButtonOptions { // tslint:disable-line:no-any show?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: T) => boolean); loading?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: T) => boolean); // This prop CAN'T use with autoLoading=true disabled?: boolean | ((this: ModalButtonOptions, contentComponentInstance?: T) => boolean); - onClick?(this: ModalButtonOptions, contentComponentInstance?: T): (void | {}) | Promise<(void | {})>; + onClick?(this: ModalButtonOptions, contentComponentInstance?: T): (void | {}) | Promise; // tslint:disable-next-line:no-any - [ key: string ]: any; + [key: string]: any; } diff --git a/components/notification/demo/basic.ts b/components/notification/demo/basic.ts index 9cb28c1f100..02c7cc93a63 100644 --- a/components/notification/demo/basic.ts +++ b/components/notification/demo/basic.ts @@ -6,14 +6,15 @@ import { NzNotificationService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoNotificationBasicComponent { - - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} createBasicNotification(): void { - this.notification.blank( 'Notification Title', 'This is the content of the notification. This is the content of the notification. This is the content of the notification.'); + this.notification.blank( + 'Notification Title', + 'This is the content of the notification. This is the content of the notification. This is the content of the notification.' + ); } } diff --git a/components/notification/demo/custom-icon.ts b/components/notification/demo/custom-icon.ts index b805df12c1e..2e4294dfd7f 100644 --- a/components/notification/demo/custom-icon.ts +++ b/components/notification/demo/custom-icon.ts @@ -7,22 +7,25 @@ import { NzNotificationService } from 'ng-zorro-antd';
    - +
    Notification Title
    - This is the content of the notification. This is the content of the notification. This is the content of the notification. + This is the content of the notification. This is the content of the notification. This is the content of the + notification.
    - + `, - styles : [] + styles: [] }) export class NzDemoNotificationCustomIconComponent { - - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} createBasicNotification(template: TemplateRef<{}>): void { this.notification.template(template); diff --git a/components/notification/demo/custom-style.ts b/components/notification/demo/custom-style.ts index 7e2bbe983bf..a9e808c4e93 100644 --- a/components/notification/demo/custom-style.ts +++ b/components/notification/demo/custom-style.ts @@ -6,20 +6,22 @@ import { NzNotificationService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoNotificationCustomStyleComponent { - - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} createBasicNotification(): void { - this.notification.blank('Notification Title', 'This is the content of the notification. This is the content of the notification. This is the content of the notification.', { - nzStyle: { - width : '600px', - marginLeft: '-265px' - }, - nzClass: 'test-class' - }); + this.notification.blank( + 'Notification Title', + 'This is the content of the notification. This is the content of the notification. This is the content of the notification.', + { + nzStyle: { + width: '600px', + marginLeft: '-265px' + }, + nzClass: 'test-class' + } + ); } } diff --git a/components/notification/demo/duration.ts b/components/notification/demo/duration.ts index 0e64cc7578c..8cae578820e 100644 --- a/components/notification/demo/duration.ts +++ b/components/notification/demo/duration.ts @@ -6,13 +6,16 @@ import { NzNotificationService } from 'ng-zorro-antd'; template: ` `, - styles : [] + styles: [] }) export class NzDemoNotificationDurationComponent { createBasicNotification(): void { - this.notification.blank('Notification Title', 'I will never close automatically. I will be close automatically. I will never close automatically.', { nzDuration: 0 }); + this.notification.blank( + 'Notification Title', + 'I will never close automatically. I will be close automatically. I will never close automatically.', + { nzDuration: 0 } + ); } - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} } diff --git a/components/notification/demo/placement.ts b/components/notification/demo/placement.ts index 0897d6bb865..d5d722841cf 100644 --- a/components/notification/demo/placement.ts +++ b/components/notification/demo/placement.ts @@ -4,7 +4,11 @@ import { NzNotificationService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-notification-placement', template: ` - + @@ -12,7 +16,7 @@ import { NzNotificationService } from 'ng-zorro-antd'; `, - styles : [] + styles: [] }) export class NzDemoNotificationPlacementComponent { placement = 'topRight'; @@ -25,9 +29,11 @@ export class NzDemoNotificationPlacementComponent { this.notification.config({ nzPlacement: this.placement }); - this.notification.blank('Notification Title', 'This is the content of the notification. This is the content of the notification. This is the content of the notification.'); + this.notification.blank( + 'Notification Title', + 'This is the content of the notification. This is the content of the notification. This is the content of the notification.' + ); } - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} } diff --git a/components/notification/demo/template.ts b/components/notification/demo/template.ts index ab8c6c03bab..84a69a68237 100644 --- a/components/notification/demo/template.ts +++ b/components/notification/demo/template.ts @@ -10,10 +10,12 @@ import { NzNotificationService } from 'ng-zorro-antd'; `, - styles : [ - `button { - margin-top: 8px; - }` + styles: [ + ` + button { + margin-top: 8px; + } + ` ] }) export class NzDemoNotificationTemplateComponent { @@ -31,6 +33,5 @@ export class NzDemoNotificationTemplateComponent { }); } - constructor(private notificationService: NzNotificationService) { - } + constructor(private notificationService: NzNotificationService) {} } diff --git a/components/notification/demo/update.ts b/components/notification/demo/update.ts index 4c9986a51f9..cfb77dc5913 100644 --- a/components/notification/demo/update.ts +++ b/components/notification/demo/update.ts @@ -4,20 +4,19 @@ import { NzNotificationService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-notification-update', template: ` - + `, - styles : [] + styles: [] }) export class NzDemoNotificationUpdateComponent { - - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} createAutoUpdatingNotifications(): void { this.notification.blank('Notification Title', 'Description.', { - nzKey: 'key' - } - ); + nzKey: 'key' + }); setTimeout(() => { this.notification.blank('New Title', 'New description', { diff --git a/components/notification/demo/with-btn.ts b/components/notification/demo/with-btn.ts index 5d2533ce4b9..3959d8a5eac 100644 --- a/components/notification/demo/with-btn.ts +++ b/components/notification/demo/with-btn.ts @@ -9,22 +9,25 @@ import { NzNotificationService } from 'ng-zorro-antd';
    Notification Title
    - A function will be be called after the notification is closed (automatically after the "duration" time of manually). + A function will be be called after the notification is closed (automatically after the "duration" time of + manually).
    - +
    - + `, - styles : [] + styles: [] }) export class NzDemoNotificationWithBtnComponent { - - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} createBasicNotification(template: TemplateRef<{}>): void { this.notification.template(template); diff --git a/components/notification/demo/with-icon.ts b/components/notification/demo/with-icon.ts index f2cce88bf2d..e721708aab2 100644 --- a/components/notification/demo/with-icon.ts +++ b/components/notification/demo/with-icon.ts @@ -9,7 +9,7 @@ import { NzNotificationService } from 'ng-zorro-antd'; `, - styles : [ + styles: [ ` button { margin-right: 1em; @@ -19,10 +19,12 @@ import { NzNotificationService } from 'ng-zorro-antd'; }) export class NzDemoNotificationWithIconComponent { createNotification(type: string): void { - this.notification.create(type, 'Notification Title', - 'This is the content of the notification. This is the content of the notification. This is the content of the notification.'); + this.notification.create( + type, + 'Notification Title', + 'This is the content of the notification. This is the content of the notification. This is the content of the notification.' + ); } - constructor(private notification: NzNotificationService) { - } + constructor(private notification: NzNotificationService) {} } diff --git a/components/notification/nz-notification-config.ts b/components/notification/nz-notification-config.ts index e80477ffee3..45917f63ea2 100644 --- a/components/notification/nz-notification-config.ts +++ b/components/notification/nz-notification-config.ts @@ -8,19 +8,21 @@ export interface NzNotificationConfig extends NzMessageConfig { nzPlacement?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | string; } -export const NZ_NOTIFICATION_DEFAULT_CONFIG = new InjectionToken('NZ_NOTIFICATION_DEFAULT_CONFIG'); +export const NZ_NOTIFICATION_DEFAULT_CONFIG = new InjectionToken( + 'NZ_NOTIFICATION_DEFAULT_CONFIG' +); export const NZ_NOTIFICATION_CONFIG = new InjectionToken('NZ_NOTIFICATION_CONFIG'); export const NZ_NOTIFICATION_DEFAULT_CONFIG_PROVIDER = { - provide : NZ_NOTIFICATION_DEFAULT_CONFIG, + provide: NZ_NOTIFICATION_DEFAULT_CONFIG, useValue: { - nzTop : '24px', - nzBottom : '24px', - nzPlacement : 'topRight', - nzDuration : 4500, - nzMaxStack : 7, + nzTop: '24px', + nzBottom: '24px', + nzPlacement: 'topRight', + nzDuration: 4500, + nzMaxStack: 7, nzPauseOnHover: true, - nzAnimate : true + nzAnimate: true } }; diff --git a/components/notification/nz-notification-container.component.ts b/components/notification/nz-notification-container.component.ts index cbe7f7e12e1..15c30cef08a 100644 --- a/components/notification/nz-notification-container.component.ts +++ b/components/notification/nz-notification-container.component.ts @@ -11,22 +11,15 @@ import { Subject } from 'rxjs'; import { toCssPixel } from '../core/util'; import { NzMessageContainerComponent } from '../message/nz-message-container.component'; -import { - NzNotificationConfig, - NZ_NOTIFICATION_CONFIG, - NZ_NOTIFICATION_DEFAULT_CONFIG -} from './nz-notification-config'; -import { - NzNotificationDataFilled, - NzNotificationDataOptions -} from './nz-notification.definitions'; +import { NzNotificationConfig, NZ_NOTIFICATION_CONFIG, NZ_NOTIFICATION_DEFAULT_CONFIG } from './nz-notification-config'; +import { NzNotificationDataFilled, NzNotificationDataOptions } from './nz-notification.definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-notification-container', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-notification-container', preserveWhitespaces: false, - templateUrl : './nz-notification-container.component.html' + templateUrl: './nz-notification-container.component.html' }) export class NzNotificationContainerComponent extends NzMessageContainerComponent { config: Required; @@ -49,15 +42,11 @@ export class NzNotificationContainerComponent extends NzMessageContainerComponen * @override */ setConfig(config: NzNotificationConfig): void { - const newConfig = this.config = { ...this.config, ...config }; + const newConfig = (this.config = { ...this.config, ...config }); const placement = this.config.nzPlacement; - this.top = placement === 'topLeft' || placement === 'topRight' - ? toCssPixel(newConfig.nzTop) - : null; - this.bottom = placement === 'bottomLeft' || placement === 'bottomRight' - ? toCssPixel(newConfig.nzBottom) - : null; + this.top = placement === 'topLeft' || placement === 'topRight' ? toCssPixel(newConfig.nzTop) : null; + this.bottom = placement === 'bottomLeft' || placement === 'bottomRight' ? toCssPixel(newConfig.nzBottom) : null; this.cdr.markForCheck(); } @@ -88,10 +77,7 @@ export class NzNotificationContainerComponent extends NzMessageContainerComponen this.cdr.detectChanges(); } - private replaceNotification( - old: NzNotificationDataFilled, - _new: NzNotificationDataFilled - ): void { + private replaceNotification(old: NzNotificationDataFilled, _new: NzNotificationDataFilled): void { old.title = _new.title; old.content = _new.content; old.template = _new.template; diff --git a/components/notification/nz-notification.component.ts b/components/notification/nz-notification.component.ts index 7ccf6813290..50ef9c5404d 100644 --- a/components/notification/nz-notification.component.ts +++ b/components/notification/nz-notification.component.ts @@ -7,11 +7,11 @@ import { NzNotificationContainerComponent } from './nz-notification-container.co import { NzNotificationDataFilled } from './nz-notification.definitions'; @Component({ - encapsulation : ViewEncapsulation.None, - selector : 'nz-notification', + encapsulation: ViewEncapsulation.None, + selector: 'nz-notification', preserveWhitespaces: false, - animations : [ notificationMotion ], - templateUrl : './nz-notification.component.html' + animations: [notificationMotion], + templateUrl: './nz-notification.component.html' }) export class NzNotificationComponent extends NzMessageComponent { @Input() nzMessage: NzNotificationDataFilled; @@ -26,7 +26,7 @@ export class NzNotificationComponent extends NzMessageComponent { get state(): string | undefined { if (this.nzMessage.state === 'enter') { - if ((this.container.config.nzPlacement === 'topLeft') || (this.container.config.nzPlacement === 'bottomLeft')) { + if (this.container.config.nzPlacement === 'topLeft' || this.container.config.nzPlacement === 'bottomLeft') { return 'enterLeft'; } else { return 'enterRight'; diff --git a/components/notification/nz-notification.module.ts b/components/notification/nz-notification.module.ts index 07a5067b45b..a3eb01e7347 100644 --- a/components/notification/nz-notification.module.ts +++ b/components/notification/nz-notification.module.ts @@ -9,10 +9,9 @@ import { NzNotificationComponent } from './nz-notification.component'; import { NzNotificationService } from './nz-notification.service'; @NgModule({ - imports : [ CommonModule, OverlayModule, NzIconModule ], - declarations : [ NzNotificationComponent, NzNotificationContainerComponent ], - providers : [ NZ_NOTIFICATION_DEFAULT_CONFIG_PROVIDER, NzNotificationService ], - entryComponents: [ NzNotificationContainerComponent ] + imports: [CommonModule, OverlayModule, NzIconModule], + declarations: [NzNotificationComponent, NzNotificationContainerComponent], + providers: [NZ_NOTIFICATION_DEFAULT_CONFIG_PROVIDER, NzNotificationService], + entryComponents: [NzNotificationContainerComponent] }) -export class NzNotificationModule { -} +export class NzNotificationModule {} diff --git a/components/notification/nz-notification.service.ts b/components/notification/nz-notification.service.ts index 7d753700f49..a133a5ebc88 100644 --- a/components/notification/nz-notification.service.ts +++ b/components/notification/nz-notification.service.ts @@ -10,14 +10,12 @@ import { NzNotificationData, NzNotificationDataFilled, NzNotificationDataOptions @Injectable({ providedIn: 'root' }) -export class NzNotificationService extends NzMessageBaseService { - - constructor( - overlay: Overlay, - injector: Injector, - cfr: ComponentFactoryResolver, - appRef: ApplicationRef - ) { +export class NzNotificationService extends NzMessageBaseService< + NzNotificationContainerComponent, + NzNotificationData, + NzNotificationConfig +> { + constructor(overlay: Overlay, injector: Injector, cfr: ComponentFactoryResolver, appRef: ApplicationRef) { super(overlay, NzNotificationContainerComponent, injector, cfr, appRef, 'notification-'); } @@ -42,7 +40,12 @@ export class NzNotificationService extends NzMessageBaseService { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzNotificationModule, NoopAnimationsModule ], - declarations: [ DemoAppComponent ], - providers : [ { provide: NZ_NOTIFICATION_CONFIG, useValue: { nzMaxStack: 2 } } ] // Override default config + imports: [NzNotificationModule, NoopAnimationsModule], + declarations: [DemoAppComponent], + providers: [{ provide: NZ_NOTIFICATION_CONFIG, useValue: { nzMaxStack: 2 } }] // Override default config }); TestBed.compileComponents(); })); - beforeEach(inject([ NzNotificationService, OverlayContainer ], (n: NzNotificationService, oc: OverlayContainer) => { + beforeEach(inject([NzNotificationService, OverlayContainer], (n: NzNotificationService, oc: OverlayContainer) => { notificationService = n; overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); @@ -49,45 +49,45 @@ describe('NzNotification', () => { fixture = TestBed.createComponent(DemoAppComponent); }); - it('should open a message box with success', (() => { + it('should open a message box with success', () => { notificationService.success('test-title', 'SUCCESS'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('SUCCESS'); expect(overlayContainerElement.querySelector('.ant-notification-notice-icon-success')).not.toBeNull(); - })); + }); - it('should open a message box with error', (() => { + it('should open a message box with error', () => { notificationService.error('test-title', 'ERROR'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('ERROR'); expect(overlayContainerElement.querySelector('.ant-notification-notice-icon-error')).not.toBeNull(); - })); + }); - it('should open a message box with warning', (() => { + it('should open a message box with warning', () => { notificationService.warning('test-title', 'WARNING'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('WARNING'); expect(overlayContainerElement.querySelector('.ant-notification-notice-icon-warning')).not.toBeNull(); - })); + }); - it('should open a message box with info', (() => { + it('should open a message box with info', () => { notificationService.info('test-title', 'INFO'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('INFO'); expect(overlayContainerElement.querySelector('.ant-notification-notice-icon-info')).not.toBeNull(); - })); + }); - it('should open a message box with blank', (() => { + it('should open a message box with blank', () => { notificationService.blank('test-title', 'BLANK'); fixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('BLANK'); expect(overlayContainerElement.querySelector('.ant-notification-notice-icon')).toBeNull(); - })); + }); it('should auto closed by 1s', fakeAsync(() => { notificationService.create('', '', 'EXISTS', { nzDuration: 1000 }); @@ -126,7 +126,7 @@ describe('NzNotification', () => { })); it('should keep the balance of messages length and then remove all', fakeAsync(() => { - [ 1, 2, 3 ].forEach(id => { + [1, 2, 3].forEach(id => { const content = `SUCCESS-${id}`; notificationService.success('', content); fixture.detectChanges(); diff --git a/components/pagination/demo/basic.ts b/components/pagination/demo/basic.ts index 050c3988d98..0bd157a9292 100644 --- a/components/pagination/demo/basic.ts +++ b/components/pagination/demo/basic.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-basic', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationBasicComponent { -} +export class NzDemoPaginationBasicComponent {} diff --git a/components/pagination/demo/changer.ts b/components/pagination/demo/changer.ts index 428644a06ff..5ea359163b8 100644 --- a/components/pagination/demo/changer.ts +++ b/components/pagination/demo/changer.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-changer', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationChangerComponent { -} +export class NzDemoPaginationChangerComponent {} diff --git a/components/pagination/demo/controlled.ts b/components/pagination/demo/controlled.ts index f220216f9a0..b92aff46758 100644 --- a/components/pagination/demo/controlled.ts +++ b/components/pagination/demo/controlled.ts @@ -3,7 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-controlled', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationControlledComponent { } +export class NzDemoPaginationControlledComponent {} diff --git a/components/pagination/demo/itemRender.ts b/components/pagination/demo/itemRender.ts index 7d95ff627ed..be7a84fe4b6 100644 --- a/components/pagination/demo/itemRender.ts +++ b/components/pagination/demo/itemRender.ts @@ -5,12 +5,11 @@ import { Component } from '@angular/core'; template: ` - Previous - Next - {{page}} + Previous + Next + {{ page }} `, - styles : [] + styles: [] }) -export class NzDemoPaginationItemRenderComponent { -} +export class NzDemoPaginationItemRenderComponent {} diff --git a/components/pagination/demo/jump.ts b/components/pagination/demo/jump.ts index b7ce6f5a525..2a8622efb9b 100644 --- a/components/pagination/demo/jump.ts +++ b/components/pagination/demo/jump.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-jump', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationJumpComponent { -} +export class NzDemoPaginationJumpComponent {} diff --git a/components/pagination/demo/mini.ts b/components/pagination/demo/mini.ts index 4e85dd2aa90..0a51520eb61 100644 --- a/components/pagination/demo/mini.ts +++ b/components/pagination/demo/mini.ts @@ -4,13 +4,24 @@ import { Component } from '@angular/core'; selector: 'nz-demo-pagination-mini', template: ` -
    - -
    - - Total {{total}} items +
    + +
    + + Total {{ total }} items `, - styles : [] + styles: [] }) export class NzDemoPaginationMiniComponent { current = 1; diff --git a/components/pagination/demo/more.ts b/components/pagination/demo/more.ts index 3802224d62a..d3d1843e933 100644 --- a/components/pagination/demo/more.ts +++ b/components/pagination/demo/more.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-more', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationMoreComponent { -} +export class NzDemoPaginationMoreComponent {} diff --git a/components/pagination/demo/simple.ts b/components/pagination/demo/simple.ts index 198f9b8d865..e72c83120d9 100644 --- a/components/pagination/demo/simple.ts +++ b/components/pagination/demo/simple.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-pagination-simple', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoPaginationSimpleComponent { -} +export class NzDemoPaginationSimpleComponent {} diff --git a/components/pagination/demo/total.ts b/components/pagination/demo/total.ts index fa44f3a9c6d..f766fda115d 100644 --- a/components/pagination/demo/total.ts +++ b/components/pagination/demo/total.ts @@ -4,16 +4,13 @@ import { Component } from '@angular/core'; selector: 'nz-demo-pagination-total', template: ` -
    +
    - - Total {{total}} items - + Total {{ total }} items - {{range[0]}}-{{range[1]}} of {{total}} items + {{ range[0] }}-{{ range[1] }} of {{ total }} items `, - styles : [] + styles: [] }) -export class NzDemoPaginationTotalComponent { -} +export class NzDemoPaginationTotalComponent {} diff --git a/components/pagination/nz-pagination.component.ts b/components/pagination/nz-pagination.component.ts index a4341e05840..58e83ff7bc2 100644 --- a/components/pagination/nz-pagination.component.ts +++ b/components/pagination/nz-pagination.component.ts @@ -20,11 +20,11 @@ import { toNumber, InputBoolean, InputNumber } from '../core/util/convert'; import { NzI18nService } from '../i18n/nz-i18n.service'; @Component({ - selector : 'nz-pagination', + selector: 'nz-pagination', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-pagination.component.html' + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-pagination.component.html' }) export class NzPaginationComponent implements OnInit, OnDestroy, OnChanges { // tslint:disable-next-line:no-any @@ -34,11 +34,14 @@ export class NzPaginationComponent implements OnInit, OnDestroy, OnChanges { private $destroy = new Subject(); @Output() readonly nzPageSizeChange: EventEmitter = new EventEmitter(); @Output() readonly nzPageIndexChange: EventEmitter = new EventEmitter(); - @Input() nzShowTotal: TemplateRef<{ $implicit: number, range: [ number, number ] }>; + @Input() nzShowTotal: TemplateRef<{ $implicit: number; range: [number, number] }>; @Input() nzInTable = false; @Input() nzSize: 'default' | 'small' = 'default'; - @Input() nzPageSizeOptions = [ 10, 20, 30, 40 ]; - @Input() @ViewChild('renderItemTemplate') nzItemRender: TemplateRef<{ $implicit: 'page' | 'prev' | 'next', page: number }>; + @Input() nzPageSizeOptions = [10, 20, 30, 40]; + @Input() @ViewChild('renderItemTemplate') nzItemRender: TemplateRef<{ + $implicit: 'page' | 'prev' | 'next'; + page: number; + }>; @Input() @InputBoolean() nzShowSizeChanger = false; @Input() @InputBoolean() nzHideOnSinglePage = false; @Input() @InputBoolean() nzShowQuickJumper = false; @@ -140,20 +143,17 @@ export class NzPaginationComponent implements OnInit, OnDestroy, OnChanges { } get ranges(): number[] { - return [ (this.nzPageIndex - 1) * this.nzPageSize + 1, Math.min(this.nzPageIndex * this.nzPageSize, this.nzTotal) ]; + return [(this.nzPageIndex - 1) * this.nzPageSize + 1, Math.min(this.nzPageIndex * this.nzPageSize, this.nzTotal)]; } get showAddOption(): boolean { return this.nzPageSizeOptions.indexOf(this.nzPageSize) === -1; } - constructor(private i18n: NzI18nService, private cdr: ChangeDetectorRef) { - } + constructor(private i18n: NzI18nService, private cdr: ChangeDetectorRef) {} ngOnInit(): void { - this.i18n.localeChange.pipe( - takeUntil(this.$destroy) - ).subscribe(() => { + this.i18n.localeChange.pipe(takeUntil(this.$destroy)).subscribe(() => { this.locale = this.i18n.getLocaleData('Pagination'); this.cdr.markForCheck(); }); diff --git a/components/pagination/nz-pagination.module.ts b/components/pagination/nz-pagination.module.ts index 35246d82725..81483bbcc7b 100644 --- a/components/pagination/nz-pagination.module.ts +++ b/components/pagination/nz-pagination.module.ts @@ -9,10 +9,8 @@ import { NzSelectModule } from '../select/nz-select.module'; import { NzPaginationComponent } from './nz-pagination.component'; @NgModule({ - declarations: [ NzPaginationComponent ], - exports : [ NzPaginationComponent ], - imports : [ CommonModule, FormsModule, NzSelectModule, NzI18nModule, NzIconModule ] + declarations: [NzPaginationComponent], + exports: [NzPaginationComponent], + imports: [CommonModule, FormsModule, NzSelectModule, NzI18nModule, NzIconModule] }) - -export class NzPaginationModule { -} +export class NzPaginationModule {} diff --git a/components/pagination/nz-pagination.spec.ts b/components/pagination/nz-pagination.spec.ts index ca0885e6fcd..e85e7d92cf4 100644 --- a/components/pagination/nz-pagination.spec.ts +++ b/components/pagination/nz-pagination.spec.ts @@ -13,8 +13,8 @@ describe('pagination', () => { beforeEach(async(() => { injector = TestBed.configureTestingModule({ - imports : [ NzPaginationModule, NoopAnimationsModule ], - declarations: [ NzTestPaginationComponent, NzTestPaginationRenderComponent, NzTestPaginationTotalComponent ] + imports: [NzPaginationModule, NoopAnimationsModule], + declarations: [NzTestPaginationComponent, NzTestPaginationRenderComponent, NzTestPaginationTotalComponent] }); TestBed.compileComponents(); })); @@ -40,7 +40,7 @@ describe('pagination', () => { expect(paginationElement.lastElementChild!.classList.contains('ant-pagination-next')).toBe(true); const length = paginationElement.children.length; const array = Array.prototype.slice.call(paginationElement.children).slice(1, length - 1); - expect(array[ 0 ].classList.contains('ant-pagination-item-active')).toBe(true); + expect(array[0].classList.contains('ant-pagination-item-active')).toBe(true); expect(array.every((node: HTMLElement) => node.classList.contains('ant-pagination-item'))).toBe(true); }); it('should small size className correct', () => { @@ -54,15 +54,15 @@ describe('pagination', () => { expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); const length = paginationElement.children.length; const array = Array.prototype.slice.call(paginationElement.children).slice(1, length - 1); - expect(array[ 1 ].classList.contains('ant-pagination-item-active')).toBe(true); + expect(array[1].classList.contains('ant-pagination-item-active')).toBe(true); }); it('should pageIndex change not trigger when same', () => { fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); const length = paginationElement.children.length; const array = Array.prototype.slice.call(paginationElement.children).slice(1, length - 1); - expect(array[ 0 ].classList.contains('ant-pagination-item-active')).toBe(true); - array[ 0 ].click(); + expect(array[0].classList.contains('ant-pagination-item-active')).toBe(true); + array[0].click(); fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); }); @@ -78,7 +78,7 @@ describe('pagination', () => { it('should pre button disabled', () => { fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); - (paginationElement.children[ 0 ] as HTMLElement).click(); + (paginationElement.children[0] as HTMLElement).click(); fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.pageIndex).toBe(1); @@ -87,7 +87,7 @@ describe('pagination', () => { testComponent.pageIndex = 5; fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); - (paginationElement.children[ 0 ] as HTMLElement).click(); + (paginationElement.children[0] as HTMLElement).click(); fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(1); expect(testComponent.pageIndex).toBe(4); @@ -112,7 +112,7 @@ describe('pagination', () => { it('should click pageIndex work', () => { fixture.detectChanges(); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); - (paginationElement.children[ 3 ] as HTMLElement).click(); + (paginationElement.children[3] as HTMLElement).click(); fixture.detectChanges(); expect(testComponent.pageIndex).toBe(3); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(1); @@ -127,7 +127,7 @@ describe('pagination', () => { fixture.detectChanges(); testComponent.pageIndex = 46; fixture.detectChanges(); - (paginationElement.children[ 8 ] as HTMLElement).click(); + (paginationElement.children[8] as HTMLElement).click(); fixture.detectChanges(); expect(testComponent.pageIndex).toBe(50); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(1); @@ -139,7 +139,7 @@ describe('pagination', () => { testComponent.pageIndex = 5; fixture.detectChanges(); expect(paginationElement.children.length).toBe(11); - (paginationElement.children[ 2 ] as HTMLElement).click(); + (paginationElement.children[2] as HTMLElement).click(); fixture.detectChanges(); expect(testComponent.pageIndex).toBe(1); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(1); @@ -257,7 +257,7 @@ describe('pagination', () => { fixture.detectChanges(); expect((paginationElement.firstElementChild as HTMLElement).innerText).toBe('Previous'); expect((paginationElement.lastElementChild as HTMLElement).innerText).toBe('Next'); - expect((paginationElement.children[ 1 ] as HTMLElement).innerText).toBe('2'); + expect((paginationElement.children[1] as HTMLElement).innerText).toBe('2'); }); }); describe('pagination total items', () => { @@ -311,8 +311,10 @@ describe('pagination', () => { [nzHideOnSinglePage]="hideOnSinglePage" [nzPageSizeOptions]="pageSizeOptions" [nzShowSizeChanger]="showSizeChanger" - [nzShowQuickJumper]="showQuickJumper"> - ` + [nzShowQuickJumper]="showQuickJumper" + > + + ` }) export class NzTestPaginationComponent { @ViewChild(NzPaginationComponent) nzPaginationComponent: NzPaginationComponent; @@ -324,7 +326,7 @@ export class NzTestPaginationComponent { showQuickJumper = false; showSizeChanger = false; hideOnSinglePage = false; - pageSizeOptions = [ 10, 20, 30, 40 ]; + pageSizeOptions = [10, 20, 30, 40]; simple = false; size = ''; } @@ -334,21 +336,25 @@ export class NzTestPaginationComponent { template: ` - Previous - Next - {{page * 2}} + Previous + Next + {{ page * 2 }} ` }) -export class NzTestPaginationRenderComponent { -} +export class NzTestPaginationRenderComponent {} @Component({ selector: `nz-test-pagination-total`, template: ` - + - {{range[0]}}-{{range[1]}} of {{total}} items + {{ range[0] }}-{{ range[1] }} of {{ total }} items ` }) diff --git a/components/polyfills.ts b/components/polyfills.ts index 0861e293e14..558723158fc 100644 --- a/components/polyfills.ts +++ b/components/polyfills.ts @@ -35,17 +35,15 @@ import 'core-js/es6/weak-map'; import 'core-js/es6/set'; /** IE10 and IE11 requires the following for NgClass support on SVG elements */ -import 'classlist.js'; // Run `npm install --save classlist.js`. +import 'classlist.js'; // Run `npm install --save classlist.js`. /** IE10 and IE11 requires the following for the Reflect API. */ import 'core-js/es6/reflect'; - /** Evergreen browsers require these. **/ // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. import 'core-js/es7/reflect'; - /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. @@ -63,17 +61,15 @@ import 'core-js/es7/reflect'; // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames /* -* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js -* with the following flag, it will bypass `zone.js` patch for IE/Edge -*/ + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + */ // (window as any).__Zone_enable_cross_context_check = true; /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - - +import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS diff --git a/components/popconfirm/demo/basic.ts b/components/popconfirm/demo/basic.ts index 148b299d21b..f6cba0faadc 100644 --- a/components/popconfirm/demo/basic.ts +++ b/components/popconfirm/demo/basic.ts @@ -4,11 +4,12 @@ import { NzMessageService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-popconfirm-basic', template: ` - Delete + Delete ` }) export class NzDemoPopconfirmBasicComponent { - cancel(): void { this.nzMessageService.info('click cancel'); } @@ -17,8 +18,5 @@ export class NzDemoPopconfirmBasicComponent { this.nzMessageService.info('click confirm'); } - constructor(private nzMessageService: NzMessageService) { - - } - + constructor(private nzMessageService: NzMessageService) {} } diff --git a/components/popconfirm/demo/custom-icon.ts b/components/popconfirm/demo/custom-icon.ts index 9afc37d4486..42b2b59178f 100644 --- a/components/popconfirm/demo/custom-icon.ts +++ b/components/popconfirm/demo/custom-icon.ts @@ -9,6 +9,4 @@ import { Component } from '@angular/core'; ` }) - -export class NzDemoPopconfirmCustomIconComponent { -} +export class NzDemoPopconfirmCustomIconComponent {} diff --git a/components/popconfirm/demo/dynamic-trigger.ts b/components/popconfirm/demo/dynamic-trigger.ts index 4a7e219ac1f..314a142dfcb 100644 --- a/components/popconfirm/demo/dynamic-trigger.ts +++ b/components/popconfirm/demo/dynamic-trigger.ts @@ -4,14 +4,20 @@ import { NzMessageService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-popconfirm-dynamic-trigger', template: ` - Delete a task -
    -
    + Delete a task +
    +
    Whether directly execute: ` }) - export class NzDemoPopconfirmDynamicTriggerComponent { switchValue = false; @@ -23,8 +29,5 @@ export class NzDemoPopconfirmDynamicTriggerComponent { this.nzMessageService.info('click confirm'); } - constructor(private nzMessageService: NzMessageService) { - - } - + constructor(private nzMessageService: NzMessageService) {} } diff --git a/components/popconfirm/demo/locale.ts b/components/popconfirm/demo/locale.ts index e48efc65852..a719136bad9 100644 --- a/components/popconfirm/demo/locale.ts +++ b/components/popconfirm/demo/locale.ts @@ -4,12 +4,18 @@ import { NzMessageService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-popconfirm-locale', template: ` - delete + delete ` }) - export class NzDemoPopconfirmLocaleComponent { - cancel(): void { this.nzMessageService.info('click cancel'); } @@ -18,7 +24,5 @@ export class NzDemoPopconfirmLocaleComponent { this.nzMessageService.info('click confirm'); } - constructor(private nzMessageService: NzMessageService) { - - } + constructor(private nzMessageService: NzMessageService) {} } diff --git a/components/popconfirm/demo/placement.ts b/components/popconfirm/demo/placement.ts index 8da70d2e455..7388d670c02 100644 --- a/components/popconfirm/demo/placement.ts +++ b/components/popconfirm/demo/placement.ts @@ -5,37 +5,146 @@ import { NzMessageService } from 'ng-zorro-antd'; selector: 'nz-demo-popconfirm-placement', template: `
    - - - + + +
    - - - + + +
    - - - + + +
    - - - + + +
    `, - styles : [ ` - button { - margin-right: 8px; - margin-bottom: 8px; - width: 70px; - text-align: center; - padding: 0; - } - ` ] + styles: [ + ` + button { + margin-right: 8px; + margin-bottom: 8px; + width: 70px; + text-align: center; + padding: 0; + } + ` + ] }) - export class NzDemoPopconfirmPlacementComponent { cancel(): void { this.nzMessageService.info('click cancel'); @@ -45,7 +154,5 @@ export class NzDemoPopconfirmPlacementComponent { this.nzMessageService.info('click confirm'); } - constructor(private nzMessageService: NzMessageService) { - - } + constructor(private nzMessageService: NzMessageService) {} } diff --git a/components/popconfirm/nz-popconfirm.component.ts b/components/popconfirm/nz-popconfirm.component.ts index 5df207c64eb..7fdbc300060 100644 --- a/components/popconfirm/nz-popconfirm.component.ts +++ b/components/popconfirm/nz-popconfirm.component.ts @@ -16,17 +16,19 @@ import { InputBoolean } from '../core/util/convert'; import { NzToolTipComponent } from '../tooltip/nz-tooltip.component'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-popconfirm', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-popconfirm', preserveWhitespaces: false, - animations : [ zoomBigMotion ], - templateUrl : './nz-popconfirm.component.html', - styles : [ ` - .ant-popover { - position: relative; - } - ` ] + animations: [zoomBigMotion], + templateUrl: './nz-popconfirm.component.html', + styles: [ + ` + .ant-popover { + position: relative; + } + ` + ] }) export class NzPopconfirmComponent extends NzToolTipComponent { _prefix = 'ant-popover-placement'; diff --git a/components/popconfirm/nz-popconfirm.directive.ts b/components/popconfirm/nz-popconfirm.directive.ts index 77b8a858556..a8397ef52ee 100644 --- a/components/popconfirm/nz-popconfirm.directive.ts +++ b/components/popconfirm/nz-popconfirm.directive.ts @@ -3,12 +3,14 @@ import { ComponentFactoryResolver, Directive, ElementRef, - EventEmitter, Host, + EventEmitter, + Host, Input, OnInit, Optional, Output, - Renderer2, TemplateRef, + Renderer2, + TemplateRef, ViewContainerRef } from '@angular/core'; @@ -70,9 +72,12 @@ export class NzPopconfirmDirective extends NzTooltipDirective implements OnInit this.tooltip = tooltipComponent.instance; this.tooltip.noAnimation = this.noAnimation; // Remove element when use directive https://github.com/NG-ZORRO/ng-zorro-antd/issues/1967 - this.renderer.removeChild(this.renderer.parentNode(this.elementRef.nativeElement), tooltipComponent.location.nativeElement); + this.renderer.removeChild( + this.renderer.parentNode(this.elementRef.nativeElement), + tooltipComponent.location.nativeElement + ); this.isDynamicTooltip = true; - this.needProxyProperties.forEach(property => this.updateCompValue(property, this[ property ])); + this.needProxyProperties.forEach(property => this.updateCompValue(property, this[property])); const visible_ = this.tooltip.nzVisibleChange.pipe(distinctUntilChanged()).subscribe(data => { this.visible = data; this.nzVisibleChange.emit(data); diff --git a/components/popconfirm/nz-popconfirm.module.ts b/components/popconfirm/nz-popconfirm.module.ts index 07e2bc8d329..3541e8fa05d 100644 --- a/components/popconfirm/nz-popconfirm.module.ts +++ b/components/popconfirm/nz-popconfirm.module.ts @@ -13,9 +13,9 @@ import { NzPopconfirmComponent } from './nz-popconfirm.component'; import { NzPopconfirmDirective } from './nz-popconfirm.directive'; @NgModule({ - declarations : [ NzPopconfirmComponent, NzPopconfirmDirective ], - exports : [ NzPopconfirmComponent, NzPopconfirmDirective ], - imports : [ + declarations: [NzPopconfirmComponent, NzPopconfirmDirective], + exports: [NzPopconfirmComponent, NzPopconfirmDirective], + imports: [ CommonModule, NzButtonModule, OverlayModule, @@ -25,8 +25,6 @@ import { NzPopconfirmDirective } from './nz-popconfirm.directive'; NzOverlayModule, NzNoAnimationModule ], - entryComponents: [ NzPopconfirmComponent ] + entryComponents: [NzPopconfirmComponent] }) - -export class NzPopconfirmModule { -} +export class NzPopconfirmModule {} diff --git a/components/popconfirm/nz-popconfirm.spec.ts b/components/popconfirm/nz-popconfirm.spec.ts index 003cb7d9201..d5348c4c1d5 100644 --- a/components/popconfirm/nz-popconfirm.spec.ts +++ b/components/popconfirm/nz-popconfirm.spec.ts @@ -14,14 +14,14 @@ describe('NzPopconfirm', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzPopconfirmModule, NoopAnimationsModule, NzToolTipModule, NzIconTestModule ], - declarations: [ NzpopconfirmTestWrapperComponent, NzpopconfirmTestNewComponent ] + imports: [NzPopconfirmModule, NoopAnimationsModule, NzToolTipModule, NzIconTestModule], + declarations: [NzpopconfirmTestWrapperComponent, NzpopconfirmTestNewComponent] }); TestBed.compileComponents(); })); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); @@ -170,7 +170,9 @@ describe('NzPopconfirm', () => { const triggerElement = component.stringTemplate.nativeElement; dispatchMouseEvent(triggerElement, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain('title-string'); + expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain( + 'title-string' + ); dispatchMouseEvent(overlayContainerElement.querySelector('.cdk-overlay-backdrop')!, 'click'); tick(); fixture.detectChanges(); @@ -183,18 +185,26 @@ describe('NzPopconfirm', () => { const triggerElement = component.stringTemplate.nativeElement; dispatchMouseEvent(triggerElement, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[ 0 ].textContent).toContain('cancel-text'); - expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[ 1 ].textContent).toContain('ok-text'); - expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[ 1 ].classList).not.toContain('ant-btn-primary'); + expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[0].textContent).toContain( + 'cancel-text' + ); + expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[1].textContent).toContain( + 'ok-text' + ); + expect(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[1].classList).not.toContain( + 'ant-btn-primary' + ); }); it('should cancel work', fakeAsync(() => { const triggerElement = component.stringTemplate.nativeElement; dispatchMouseEvent(triggerElement, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain('title-string'); + expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain( + 'title-string' + ); expect(component.confirm).toHaveBeenCalledTimes(0); expect(component.cancel).toHaveBeenCalledTimes(0); - dispatchMouseEvent(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[ 0 ], 'click'); + dispatchMouseEvent(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[0], 'click'); tick(); fixture.detectChanges(); tick(500); // Wait for animations @@ -208,10 +218,12 @@ describe('NzPopconfirm', () => { const triggerElement = component.stringTemplate.nativeElement; dispatchMouseEvent(triggerElement, 'click'); fixture.detectChanges(); - expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain('title-string'); + expect(overlayContainerElement.querySelector('.ant-popover-message-title')!.textContent).toContain( + 'title-string' + ); expect(component.confirm).toHaveBeenCalledTimes(0); expect(component.cancel).toHaveBeenCalledTimes(0); - dispatchMouseEvent(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[ 1 ], 'click'); + dispatchMouseEvent(overlayContainerElement.querySelectorAll('.ant-popover-buttons button')[1], 'click'); tick(); fixture.detectChanges(); tick(500); // Wait for animations @@ -267,28 +279,30 @@ describe('NzPopconfirm', () => { @Component({ selector: 'nz-popconfirm-test-new', template: ` - + Delete - + Delete - + Delete title-template @@ -319,20 +333,23 @@ export class NzpopconfirmTestNewComponent { - - Show with icon - + Show with icon Show Show - Show + Show - + Show ` @@ -354,9 +371,7 @@ export class NzpopconfirmTestWrapperComponent { executeCondition: boolean; @ViewChild('executeTrigger') executeTrigger: ElementRef; - onConfirm(): void { - } + onConfirm(): void {} - onCancel(): void { - } + onCancel(): void {} } diff --git a/components/popover/demo/arrow-point-at-center.ts b/components/popover/demo/arrow-point-at-center.ts index b3ffe809f22..c68a7f629d6 100644 --- a/components/popover/demo/arrow-point-at-center.ts +++ b/components/popover/demo/arrow-point-at-center.ts @@ -3,15 +3,20 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-popover-arrow-point-at-center', template: ` - - + + `, - styles : [ - `button { - margin-right: 8px; - margin-bottom: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + margin-bottom: 8px; + } + ` ] }) -export class NzDemoPopoverArrowPointAtCenterComponent { -} +export class NzDemoPopoverArrowPointAtCenterComponent {} diff --git a/components/popover/demo/basic.ts b/components/popover/demo/basic.ts index 85c40629b26..527cc5b3264 100644 --- a/components/popover/demo/basic.ts +++ b/components/popover/demo/basic.ts @@ -1,19 +1,11 @@ -import { - Component -} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-popover-basic', template: ` - ` }) -export class NzDemoPopoverBasicComponent { -} +export class NzDemoPopoverBasicComponent {} diff --git a/components/popover/demo/control.ts b/components/popover/demo/control.ts index 83ba5ba1ae3..4fe7a19f46d 100644 --- a/components/popover/demo/control.ts +++ b/components/popover/demo/control.ts @@ -11,11 +11,12 @@ import { Component } from '@angular/core'; [(nzVisible)]="visible" (nzVisibleChange)="change($event)" nzTrigger="click" - [nzContent]="contentTemplate"> + [nzContent]="contentTemplate" + > Click me - Close + Close ` }) diff --git a/components/popover/demo/placement.ts b/components/popover/demo/placement.ts index b51fd7ab663..c65bba2c466 100644 --- a/components/popover/demo/placement.ts +++ b/components/popover/demo/placement.ts @@ -30,16 +30,16 @@ import { Component } from '@angular/core'; `, - styles : [ ` - button { - margin-right: 8px; - margin-bottom: 8px; - width: 70px; - text-align: center; - padding: 0; - } - ` ] + styles: [ + ` + button { + margin-right: 8px; + margin-bottom: 8px; + width: 70px; + text-align: center; + padding: 0; + } + ` + ] }) - -export class NzDemoPopoverPlacementComponent { -} +export class NzDemoPopoverPlacementComponent {} diff --git a/components/popover/demo/template.ts b/components/popover/demo/template.ts index 234a73572f7..edc0a3b8a9e 100644 --- a/components/popover/demo/template.ts +++ b/components/popover/demo/template.ts @@ -1,20 +1,13 @@ -import { - Component -} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-popover-template', template: ` - Title Content ` }) -export class NzDemoPopoverTemplateComponent { -} +export class NzDemoPopoverTemplateComponent {} diff --git a/components/popover/demo/triggerType.ts b/components/popover/demo/triggerType.ts index 389fd45b5a1..d57b5db0a37 100644 --- a/components/popover/demo/triggerType.ts +++ b/components/popover/demo/triggerType.ts @@ -13,13 +13,12 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` button { margin-right: 8px; } ` ] }) -export class NzDemoPopoverTriggerTypeComponent { -} +export class NzDemoPopoverTriggerTypeComponent {} diff --git a/components/popover/nz-popover.component.ts b/components/popover/nz-popover.component.ts index 80c06521df6..a988c740eab 100644 --- a/components/popover/nz-popover.component.ts +++ b/components/popover/nz-popover.component.ts @@ -16,17 +16,19 @@ import { isNotNil } from '../core/util'; import { NzToolTipComponent } from '../tooltip/nz-tooltip.component'; @Component({ - selector : 'nz-popover', - animations : [ zoomBigMotion ], - templateUrl : './nz-popover.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: 'nz-popover', + animations: [zoomBigMotion], + templateUrl: './nz-popover.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - styles : [ ` - .ant-popover { - position: relative; - } - ` ] + styles: [ + ` + .ant-popover { + position: relative; + } + ` + ] }) export class NzPopoverComponent extends NzToolTipComponent { _prefix = 'ant-popover-placement'; @@ -40,8 +42,9 @@ export class NzPopoverComponent extends NzToolTipComponent { } protected isContentEmpty(): boolean { - const isTitleEmpty = this.nzTitle instanceof TemplateRef ? false : (this.nzTitle === '' || !isNotNil(this.nzTitle)); - const isContentEmpty = this.nzContent instanceof TemplateRef ? false : (this.nzContent === '' || !isNotNil(this.nzContent)); + const isTitleEmpty = this.nzTitle instanceof TemplateRef ? false : this.nzTitle === '' || !isNotNil(this.nzTitle); + const isContentEmpty = + this.nzContent instanceof TemplateRef ? false : this.nzContent === '' || !isNotNil(this.nzContent); return isTitleEmpty && isContentEmpty; } } diff --git a/components/popover/nz-popover.module.ts b/components/popover/nz-popover.module.ts index 80e7e7ac857..b493b52438d 100644 --- a/components/popover/nz-popover.module.ts +++ b/components/popover/nz-popover.module.ts @@ -10,11 +10,9 @@ import { NzPopoverComponent } from './nz-popover.component'; import { NzPopoverDirective } from './nz-popover.directive'; @NgModule({ - entryComponents: [ NzPopoverComponent ], - exports : [ NzPopoverDirective, NzPopoverComponent ], - declarations : [ NzPopoverDirective, NzPopoverComponent ], - imports : [ CommonModule, OverlayModule, NzAddOnModule, NzOverlayModule, NzNoAnimationModule ] + entryComponents: [NzPopoverComponent], + exports: [NzPopoverDirective, NzPopoverComponent], + declarations: [NzPopoverDirective, NzPopoverComponent], + imports: [CommonModule, OverlayModule, NzAddOnModule, NzOverlayModule, NzNoAnimationModule] }) - -export class NzPopoverModule { -} +export class NzPopoverModule {} diff --git a/components/popover/nz-popover.spec.ts b/components/popover/nz-popover.spec.ts index b13664312ba..3d7d702edc2 100644 --- a/components/popover/nz-popover.spec.ts +++ b/components/popover/nz-popover.spec.ts @@ -15,14 +15,14 @@ describe('NzPopover', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzPopoverModule, NoopAnimationsModule, NzToolTipModule, NzIconTestModule ], - declarations: [ NzPopoverTestWrapperComponent, NzPopoverTestNewComponent ] + imports: [NzPopoverModule, NoopAnimationsModule, NzToolTipModule, NzIconTestModule], + declarations: [NzPopoverTestWrapperComponent, NzPopoverTestNewComponent] }); TestBed.compileComponents(); })); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); @@ -143,7 +143,9 @@ describe('NzPopover', () => { tick(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-popover-title')!.textContent).toContain('title-string'); - expect(overlayContainerElement.querySelector('.ant-popover-inner-content')!.textContent).toContain('content-string'); + expect(overlayContainerElement.querySelector('.ant-popover-inner-content')!.textContent).toContain( + 'content-string' + ); // Move out from the trigger element to hide it dispatchMouseEvent(triggerElement, 'mouseleave'); @@ -167,7 +169,9 @@ describe('NzPopover', () => { tick(); fixture.detectChanges(); expect(overlayContainerElement.querySelector('.ant-popover-title')!.textContent).toContain('title-template'); - expect(overlayContainerElement.querySelector('.ant-popover-inner-content')!.textContent).toContain('content-template'); + expect(overlayContainerElement.querySelector('.ant-popover-inner-content')!.textContent).toContain( + 'content-template' + ); // Move out from the trigger element to hide it dispatchMouseEvent(triggerElement, 'mouseleave'); @@ -219,9 +223,7 @@ export class NzPopoverTestNewComponent { - - Show with icon - + Show with icon Show diff --git a/components/progress/demo/circle-dynamic.ts b/components/progress/demo/circle-dynamic.ts index 6febfb90d00..9583cb22398 100644 --- a/components/progress/demo/circle-dynamic.ts +++ b/components/progress/demo/circle-dynamic.ts @@ -27,4 +27,3 @@ export class NzDemoProgressCircleDynamicComponent { } } } - diff --git a/components/progress/demo/circle-mini.ts b/components/progress/demo/circle-mini.ts index 3d481cc0854..a28dc816bba 100644 --- a/components/progress/demo/circle-mini.ts +++ b/components/progress/demo/circle-mini.ts @@ -7,7 +7,7 @@ import { Component } from '@angular/core'; `, - styles : [ + styles: [ ` nz-progress { margin-right: 8px; @@ -17,4 +17,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoProgressCircleMiniComponent { } +export class NzDemoProgressCircleMiniComponent {} diff --git a/components/progress/demo/circle.ts b/components/progress/demo/circle.ts index 734ccbce143..d87a890b3da 100644 --- a/components/progress/demo/circle.ts +++ b/components/progress/demo/circle.ts @@ -7,8 +7,8 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` nz-progress { margin-right: 8px; margin-bottom: 8px; @@ -17,5 +17,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoProgressCircleComponent { -} +export class NzDemoProgressCircleComponent {} diff --git a/components/progress/demo/dashboard.ts b/components/progress/demo/dashboard.ts index 6906013536a..2c766b9b211 100644 --- a/components/progress/demo/dashboard.ts +++ b/components/progress/demo/dashboard.ts @@ -6,4 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoProgressDashboardComponent { } +export class NzDemoProgressDashboardComponent {} diff --git a/components/progress/demo/format.ts b/components/progress/demo/format.ts index 514246384f0..df2ddfa1fa7 100644 --- a/components/progress/demo/format.ts +++ b/components/progress/demo/format.ts @@ -1,4 +1,4 @@ -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-progress-format', @@ -6,7 +6,7 @@ import {Component} from '@angular/core'; `, - styles : [ + styles: [ ` nz-progress { margin-right: 8px; diff --git a/components/progress/demo/line-mini.ts b/components/progress/demo/line-mini.ts index 7401dbc25c2..63ca5131cfe 100644 --- a/components/progress/demo/line-mini.ts +++ b/components/progress/demo/line-mini.ts @@ -12,5 +12,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoProgressLineMiniComponent { -} +export class NzDemoProgressLineMiniComponent {} diff --git a/components/progress/demo/line.ts b/components/progress/demo/line.ts index dcaa7f2a9bb..df4ddfe7d11 100644 --- a/components/progress/demo/line.ts +++ b/components/progress/demo/line.ts @@ -10,4 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoProgressLineComponent { } +export class NzDemoProgressLineComponent {} diff --git a/components/progress/demo/segment.ts b/components/progress/demo/segment.ts index 08638660413..a505b8ab698 100644 --- a/components/progress/demo/segment.ts +++ b/components/progress/demo/segment.ts @@ -8,4 +8,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoProgressSegmentComponent { } +export class NzDemoProgressSegmentComponent {} diff --git a/components/progress/nz-progress.component.ts b/components/progress/nz-progress.component.ts index 993c1c2aaff..6bd5d5ab6aa 100644 --- a/components/progress/nz-progress.component.ts +++ b/components/progress/nz-progress.component.ts @@ -1,8 +1,4 @@ -import { - Component, - Input, - OnInit -} from '@angular/core'; +import { Component, Input, OnInit } from '@angular/core'; import { ThemeType } from '@ant-design/icons-angular'; export type NzProgressGapPositionType = 'top' | 'bottom' | 'left' | 'right'; @@ -12,9 +8,9 @@ export type NzProgressStrokeLinecapType = 'round' | 'square'; import { isNotNil } from '../core/util/check'; @Component({ - selector : 'nz-progress', + selector: 'nz-progress', preserveWhitespaces: false, - templateUrl : './nz-progress.component.html' + templateUrl: './nz-progress.component.html' }) export class NzProgressComponent implements OnInit { private _gapDegree = 0; @@ -27,8 +23,8 @@ export class NzProgressComponent implements OnInit { private _size = 'default'; private _type: NzProgressTypeType = 'line'; private _format = (percent: number): string => `${percent}%`; - trailPathStyle: { [ key: string ]: string }; - strokePathStyle: { [ key: string ]: string }; + trailPathStyle: { [key: string]: string }; + strokePathStyle: { [key: string]: string }; pathString: string; icon: string; iconTheme: ThemeType; @@ -37,10 +33,10 @@ export class NzProgressComponent implements OnInit { isFormatSet = false; isGapDegreeSet = false; isGapPositionSet = false; - statusColorMap: { [ key: string ]: string } = { - normal : '#108ee9', + statusColorMap: { [key: string]: string } = { + normal: '#108ee9', exception: '#ff5500', - success : '#87d068' + success: '#87d068' }; @Input() nzShowInfo = true; @Input() nzWidth = 132; @@ -148,7 +144,6 @@ export class NzProgressComponent implements OnInit { this.isGapDegreeSet = true; this.updatePathStyles(); } - } get nzGapDegree(): number { @@ -183,7 +178,7 @@ export class NzProgressComponent implements OnInit { } updatePathStyles(): void { - const radius = 50 - (this.nzStrokeWidth / 2); + const radius = 50 - this.nzStrokeWidth / 2; let beginPositionX = 0; let beginPositionY = -radius; let endPositionX = 0; @@ -212,19 +207,19 @@ export class NzProgressComponent implements OnInit { a ${radius},${radius} 0 1 1 ${-endPositionX},${endPositionY}`; const len = Math.PI * 2 * radius; this.trailPathStyle = { - strokeDasharray : `${len - this.nzGapDegree}px ${len}px`, + strokeDasharray: `${len - this.nzGapDegree}px ${len}px`, strokeDashoffset: `-${this.nzGapDegree / 2}px`, - transition : 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s' + transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s' }; this.strokePathStyle = { - strokeDasharray : `${(this.nzPercent / 100) * (len - this.nzGapDegree)}px ${len}px`, + strokeDasharray: `${(this.nzPercent / 100) * (len - this.nzGapDegree)}px ${len}px`, strokeDashoffset: `-${this.nzGapDegree / 2}px`, - transition : 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s' // eslint-disable-line + transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s' // eslint-disable-line }; } updateIcon(): void { - const isCircle = (this.nzType === 'circle' || this.nzType === 'dashboard'); + const isCircle = this.nzType === 'circle' || this.nzType === 'dashboard'; let ret = ''; if (this.nzStatus === 'success') { ret = 'check'; @@ -247,5 +242,4 @@ export class NzProgressComponent implements OnInit { this.updatePathStyles(); this.updateIcon(); } - } diff --git a/components/progress/nz-progress.module.ts b/components/progress/nz-progress.module.ts index 96a7900b66b..747bb99801a 100644 --- a/components/progress/nz-progress.module.ts +++ b/components/progress/nz-progress.module.ts @@ -5,9 +5,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzProgressComponent } from './nz-progress.component'; @NgModule({ - exports : [ NzProgressComponent ], - declarations: [ NzProgressComponent ], - imports : [ CommonModule, NzIconModule ] + exports: [NzProgressComponent], + declarations: [NzProgressComponent], + imports: [CommonModule, NzIconModule] }) -export class NzProgressModule { -} +export class NzProgressModule {} diff --git a/components/progress/nz-progress.spec.ts b/components/progress/nz-progress.spec.ts index a937ee27540..29cb6f094ef 100644 --- a/components/progress/nz-progress.spec.ts +++ b/components/progress/nz-progress.spec.ts @@ -8,8 +8,8 @@ import { NzProgressModule } from './nz-progress.module'; describe('progress', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzProgressModule ], - declarations: [ NzTestProgressLineComponent, NzTestProgressDashBoardComponent, NzTestProgressCircleComponent ] + imports: [NzProgressModule], + declarations: [NzTestProgressLineComponent, NzTestProgressDashBoardComponent, NzTestProgressCircleComponent] }); TestBed.compileComponents(); })); @@ -26,7 +26,9 @@ describe('progress', () => { }); it('should className correct', () => { fixture.detectChanges(); - expect(progress.nativeElement.firstElementChild.className).toBe('ant-progress ant-progress-status-normal ant-progress-line ant-progress-show-info'); + expect(progress.nativeElement.firstElementChild.className).toBe( + 'ant-progress ant-progress-status-normal ant-progress-line ant-progress-show-info' + ); }); it('should percent work', () => { fixture.detectChanges(); @@ -65,7 +67,7 @@ describe('progress', () => { it('should status work', () => { fixture.detectChanges(); expect(progress.nativeElement.firstElementChild!.classList).toContain('ant-progress-status-normal'); - const listOfStatus = [ 'success', 'exception', 'active', 'normal' ]; + const listOfStatus = ['success', 'exception', 'active', 'normal']; testComponent.percent = 100; listOfStatus.forEach(status => { testComponent.status = status; @@ -130,7 +132,9 @@ describe('progress', () => { }); it('should className correct', () => { fixture.detectChanges(); - expect(progress.nativeElement.firstElementChild.className).toBe('ant-progress ant-progress-status-normal ant-progress-show-info ant-progress-circle'); + expect(progress.nativeElement.firstElementChild.className).toBe( + 'ant-progress ant-progress-status-normal ant-progress-show-info ant-progress-circle' + ); }); it('should format work', () => { testComponent.format = (percent: number) => `${percent} percent`; @@ -162,24 +166,38 @@ describe('progress', () => { }); it('should width work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-inner').style.cssText).toBe('width: 132px; height: 132px; font-size: 25.8px;'); + expect(progress.nativeElement.querySelector('.ant-progress-inner').style.cssText).toBe( + 'width: 132px; height: 132px; font-size: 25.8px;' + ); testComponent.width = 100; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-inner').style.cssText).toBe('width: 100px; height: 100px; font-size: 21px;'); + expect(progress.nativeElement.querySelector('.ant-progress-inner').style.cssText).toBe( + 'width: 100px; height: 100px; font-size: 21px;' + ); }); it('should strokeWidth work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-trail').attributes.getNamedItem('stroke-width').value).toBe('6'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-trail').attributes.getNamedItem('stroke-width').value + ).toBe('6'); testComponent.strokeWidth = 10; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-trail').attributes.getNamedItem('stroke-width').value).toBe('10'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-trail').attributes.getNamedItem('stroke-width').value + ).toBe('10'); }); it('should strokeLinecap work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap').value).toBe('round'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap') + .value + ).toBe('round'); testComponent.strokeLinecap = 'square'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap').value).toBe('square'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap') + .value + ).toBe('square'); }); }); describe('progress circle', () => { @@ -195,7 +213,9 @@ describe('progress', () => { }); it('should className correct', () => { fixture.detectChanges(); - expect(progress.nativeElement.firstElementChild.className).toBe('ant-progress ant-progress-status-normal ant-progress-show-info ant-progress-circle'); + expect(progress.nativeElement.firstElementChild.className).toBe( + 'ant-progress ant-progress-status-normal ant-progress-show-info ant-progress-circle' + ); }); it('should gapDegree work', () => { fixture.detectChanges(); @@ -206,33 +226,53 @@ describe('progress', () => { }); it('should gapPosition work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe(`M 50,50 m 0,-47\n a 47,47 0 1 1 0,94\n a 47,47 0 1 1 0,-94`); + expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe( + `M 50,50 m 0,-47\n a 47,47 0 1 1 0,94\n a 47,47 0 1 1 0,-94` + ); testComponent.gapPosition = 'left'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe(`M 50,50 m -47,0\n a 47,47 0 1 1 94,0\n a 47,47 0 1 1 -94,0`); + expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe( + `M 50,50 m -47,0\n a 47,47 0 1 1 94,0\n a 47,47 0 1 1 -94,0` + ); testComponent.gapPosition = 'right'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe(`M 50,50 m 47,0\n a 47,47 0 1 1 -94,0\n a 47,47 0 1 1 94,0`); + expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe( + `M 50,50 m 47,0\n a 47,47 0 1 1 -94,0\n a 47,47 0 1 1 94,0` + ); testComponent.gapPosition = 'bottom'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe(`M 50,50 m 0,47\n a 47,47 0 1 1 0,-94\n a 47,47 0 1 1 0,94`); + expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe( + `M 50,50 m 0,47\n a 47,47 0 1 1 0,-94\n a 47,47 0 1 1 0,94` + ); testComponent.gapPosition = 'top'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe(`M 50,50 m 0,-47\n a 47,47 0 1 1 0,94\n a 47,47 0 1 1 0,-94`); + expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('d').value).toBe( + `M 50,50 m 0,-47\n a 47,47 0 1 1 0,94\n a 47,47 0 1 1 0,-94` + ); }); it('should strokeLinecap work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap').value).toBe('round'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap') + .value + ).toBe('round'); testComponent.strokeLinecap = 'square'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap').value).toBe('square'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke-linecap') + .value + ).toBe('square'); }); it('should strokeColor work', () => { fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke').value).toBe('#108ee9'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke').value + ).toBe('#108ee9'); testComponent.strokeColor = 'blue'; fixture.detectChanges(); - expect(progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke').value).toBe('blue'); + expect( + progress.nativeElement.querySelector('.ant-progress-circle-path').attributes.getNamedItem('stroke').value + ).toBe('blue'); }); }); }); @@ -249,7 +289,8 @@ describe('progress', () => { [nzStrokeWidth]="strokeWidth" [nzPercent]="percent" [nzStrokeColor]="strokeColor" - [nzStrokeLinecap]="strokeLinecap"> + [nzStrokeLinecap]="strokeLinecap" + > ` }) @@ -276,7 +317,8 @@ export class NzTestProgressLineComponent { [nzShowInfo]="showInfo" [nzStrokeWidth]="strokeWidth" [nzPercent]="percent" - [nzStrokeLinecap]="strokeLinecap"> + [nzStrokeLinecap]="strokeLinecap" + > ` }) @@ -298,7 +340,8 @@ export class NzTestProgressDashBoardComponent { [nzGapDegree]="gapDegree" [nzGapPosition]="gapPosition" [nzStrokeColor]="strokeColor" - [nzStrokeLinecap]="strokeLinecap"> + [nzStrokeLinecap]="strokeLinecap" + > ` }) diff --git a/components/radio/demo/basic.ts b/components/radio/demo/basic.ts index c1bbabe76bb..136bc46d31b 100644 --- a/components/radio/demo/basic.ts +++ b/components/radio/demo/basic.ts @@ -6,5 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoRadioBasicComponent { -} +export class NzDemoRadioBasicComponent {} diff --git a/components/radio/demo/disable.ts b/components/radio/demo/disable.ts index 1e169f524e6..6da83b97af6 100644 --- a/components/radio/demo/disable.ts +++ b/components/radio/demo/disable.ts @@ -5,10 +5,10 @@ import { Component } from '@angular/core'; template: `
    -
    +
    - +
    ` diff --git a/components/radio/demo/radiogroup-more.ts b/components/radio/demo/radiogroup-more.ts index 44855399abd..cba0b56c035 100644 --- a/components/radio/demo/radiogroup-more.ts +++ b/components/radio/demo/radiogroup-more.ts @@ -9,13 +9,12 @@ import { Component } from '@angular/core'; - `, - styles : [ - ` + styles: [ + ` [nz-radio] { display: block; } @@ -25,8 +24,8 @@ import { Component } from '@angular/core'; export class NzDemoRadioRadiogroupMoreComponent { radioValue = 'A'; style = { - display : 'block', - height : '30px', + display: 'block', + height: '30px', lineHeight: '30px' }; } diff --git a/components/radio/demo/radiogroup-options.ts b/components/radio/demo/radiogroup-options.ts index debafb52429..46004bbb1ea 100644 --- a/components/radio/demo/radiogroup-options.ts +++ b/components/radio/demo/radiogroup-options.ts @@ -5,13 +5,13 @@ import { Component } from '@angular/core'; template: `
    - + - + - +
    ` @@ -21,6 +21,6 @@ export class NzDemoRadioRadiogroupOptionsComponent { options = [ { label: 'Apple', value: 'Apple' }, { label: 'Pear', value: 'Pear' }, - { label: 'Orange', value: 'Orange' }, + { label: 'Orange', value: 'Orange' } ]; } diff --git a/components/radio/nz-radio-button.component.ts b/components/radio/nz-radio-button.component.ts index 239b0c6cca2..0ab2a63ea42 100644 --- a/components/radio/nz-radio-button.component.ts +++ b/components/radio/nz-radio-button.component.ts @@ -13,24 +13,24 @@ import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { NzRadioComponent } from './nz-radio.component'; @Component({ - selector : '[nz-radio-button]', - providers : [ + selector: '[nz-radio-button]', + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzRadioComponent), - multi : true + multi: true }, { - provide : NzRadioComponent, + provide: NzRadioComponent, useExisting: forwardRef(() => NzRadioButtonComponent) } ], - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, - templateUrl : './nz-radio-button.component.html', - host : { - '[class.ant-radio-button-wrapper-checked]' : 'checked', + templateUrl: './nz-radio-button.component.html', + host: { + '[class.ant-radio-button-wrapper-checked]': 'checked', '[class.ant-radio-button-wrapper-disabled]': 'nzDisabled' } }) diff --git a/components/radio/nz-radio-group.component.ts b/components/radio/nz-radio-group.component.ts index f1ba1cab9b0..11c9cc2eb1d 100644 --- a/components/radio/nz-radio-group.component.ts +++ b/components/radio/nz-radio-group.component.ts @@ -25,19 +25,19 @@ import { NzRadioComponent } from './nz-radio.component'; export type NzRadioButtonStyle = 'outline' | 'solid'; @Component({ - selector : 'nz-radio-group', + selector: 'nz-radio-group', preserveWhitespaces: false, - templateUrl : './nz-radio-group.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ + templateUrl: './nz-radio-group.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzRadioGroupComponent), - multi : true + multi: true } ], - host : { + host: { '[class.ant-radio-group-large]': `nzSize === 'large'`, '[class.ant-radio-group-small]': `nzSize === 'small'`, '[class.ant-radio-group-solid]': `nzButtonStyle === 'solid'` @@ -79,33 +79,34 @@ export class NzRadioGroupComponent implements AfterContentInit, ControlValueAcce } ngAfterContentInit(): void { - this.radios.changes.pipe( - startWith(null), - takeUntil(this.destroy$) - ).subscribe(() => { - this.updateChildrenStatus(); - if (this.selectSubscription) { - this.selectSubscription.unsubscribe(); - } - this.selectSubscription = merge(...this.radios.map(radio => radio.select$)).pipe( + this.radios.changes + .pipe( + startWith(null), takeUntil(this.destroy$) - ).subscribe((radio) => { - if (this.value !== radio.nzValue) { - this.value = radio.nzValue; - this.updateChildrenStatus(); - this.onChange(this.value); + ) + .subscribe(() => { + this.updateChildrenStatus(); + if (this.selectSubscription) { + this.selectSubscription.unsubscribe(); } + this.selectSubscription = merge(...this.radios.map(radio => radio.select$)) + .pipe(takeUntil(this.destroy$)) + .subscribe(radio => { + if (this.value !== radio.nzValue) { + this.value = radio.nzValue; + this.updateChildrenStatus(); + this.onChange(this.value); + } + }); + if (this.touchedSubscription) { + this.touchedSubscription.unsubscribe(); + } + this.touchedSubscription = merge(...this.radios.map(radio => radio.touched$)) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + Promise.resolve().then(() => this.onTouched()); + }); }); - if (this.touchedSubscription) { - this.touchedSubscription.unsubscribe(); - } - this.touchedSubscription = merge(...this.radios.map(radio => radio.touched$)).pipe( - takeUntil(this.destroy$) - ).subscribe(() => { - Promise.resolve().then(() => this.onTouched()); - }); - }); - } ngOnChanges(changes: SimpleChanges): void { diff --git a/components/radio/nz-radio.component.ts b/components/radio/nz-radio.component.ts index 894f5671a3c..042293ff3f3 100644 --- a/components/radio/nz-radio.component.ts +++ b/components/radio/nz-radio.component.ts @@ -19,20 +19,20 @@ import { Subject } from 'rxjs'; import { InputBoolean } from '../core/util/convert'; @Component({ - selector : '[nz-radio]', + selector: '[nz-radio]', preserveWhitespaces: false, - templateUrl : './nz-radio.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ + templateUrl: './nz-radio.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzRadioComponent), - multi : true + multi: true } ], - host : { - '[class.ant-radio-wrapper-checked]' : 'checked', + host: { + '[class.ant-radio-wrapper-checked]': 'checked', '[class.ant-radio-wrapper-disabled]': 'nzDisabled' } }) @@ -87,7 +87,12 @@ export class NzRadioComponent implements ControlValueAccessor, AfterViewInit, On } /* tslint:disable-next-line:no-any */ - constructor(private elementRef: ElementRef, private renderer: Renderer2, private cdr: ChangeDetectorRef, private focusMonitor: FocusMonitor) { + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + private cdr: ChangeDetectorRef, + private focusMonitor: FocusMonitor + ) { this.renderer.addClass(elementRef.nativeElement, 'ant-radio-wrapper'); } diff --git a/components/radio/nz-radio.module.ts b/components/radio/nz-radio.module.ts index d099b6e3412..b234641d70e 100644 --- a/components/radio/nz-radio.module.ts +++ b/components/radio/nz-radio.module.ts @@ -7,9 +7,8 @@ import { NzRadioGroupComponent } from './nz-radio-group.component'; import { NzRadioComponent } from './nz-radio.component'; @NgModule({ - imports : [ CommonModule, FormsModule ], - exports : [ NzRadioComponent, NzRadioButtonComponent, NzRadioGroupComponent ], - declarations: [ NzRadioComponent, NzRadioButtonComponent, NzRadioGroupComponent ] + imports: [CommonModule, FormsModule], + exports: [NzRadioComponent, NzRadioButtonComponent, NzRadioGroupComponent], + declarations: [NzRadioComponent, NzRadioButtonComponent, NzRadioGroupComponent] }) -export class NzRadioModule { -} +export class NzRadioModule {} diff --git a/components/radio/nz-radio.spec.ts b/components/radio/nz-radio.spec.ts index 05743e40851..f7e89af663d 100644 --- a/components/radio/nz-radio.spec.ts +++ b/components/radio/nz-radio.spec.ts @@ -11,8 +11,16 @@ import { NzRadioModule } from './nz-radio.module'; describe('radio', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzRadioModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestRadioSingleComponent, NzTestRadioButtonComponent, NzTestRadioGroupComponent, NzTestRadioFormComponent, NzTestRadioGroupFormComponent, NzTestRadioGroupDisabledComponent, NzTestRadioGroupDisabledFormComponent ] + imports: [NzRadioModule, FormsModule, ReactiveFormsModule], + declarations: [ + NzTestRadioSingleComponent, + NzTestRadioButtonComponent, + NzTestRadioGroupComponent, + NzTestRadioFormComponent, + NzTestRadioGroupFormComponent, + NzTestRadioGroupDisabledComponent, + NzTestRadioGroupDisabledFormComponent + ] }); TestBed.compileComponents(); })); @@ -123,15 +131,15 @@ describe('radio', () => { fixture.detectChanges(); expect(testComponent.value).toBe('A'); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); - radios[ 1 ].nativeElement.click(); + radios[1].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(radios[ 0 ].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); - expect(radios[ 1 ].nativeElement.firstElementChild!.classList).toContain('ant-radio-button-checked'); + expect(radios[0].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); + expect(radios[1].nativeElement.firstElementChild!.classList).toContain('ant-radio-button-checked'); expect(testComponent.value).toBe('B'); expect(testComponent.modelChange).toHaveBeenCalledTimes(1); - radios[ 1 ].nativeElement.click(); + radios[1].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -145,11 +153,11 @@ describe('radio', () => { fixture.detectChanges(); expect(testComponent.value).toBe('A'); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); - radios[ 1 ].nativeElement.click(); + radios[1].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(radios[ 1 ].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); + expect(radios[1].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); expect(testComponent.value).toBe('A'); expect(testComponent.modelChange).toHaveBeenCalledTimes(0); })); @@ -177,11 +185,11 @@ describe('radio', () => { flush(); fixture.detectChanges(); expect(testComponent.value).toBe('A'); - radios[ 1 ].nativeElement.click(); + radios[1].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(radios[ 1 ].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); + expect(radios[1].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); expect(testComponent.value).toBe('A'); })); it('should single disable work', fakeAsync(() => { @@ -190,11 +198,11 @@ describe('radio', () => { testComponent.singleDisabled = true; fixture.detectChanges(); expect(testComponent.value).toBe('A'); - radios[ 2 ].nativeElement.click(); + radios[2].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(radios[ 2 ].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); + expect(radios[2].nativeElement.firstElementChild!.classList).not.toContain('ant-radio-button-checked'); expect(testComponent.value).toBe('A'); })); }); @@ -272,14 +280,14 @@ describe('radio', () => { it('should set disabled work', fakeAsync(() => { flush(); expect(testComponent.formGroup.get('radioGroup')!.value).toBe('B'); - radios[ 0 ].nativeElement.click(); + radios[0].nativeElement.click(); fixture.detectChanges(); expect(testComponent.formGroup.get('radioGroup')!.value).toBe('A'); testComponent.disable(); fixture.detectChanges(); flush(); fixture.detectChanges(); - radios[ 1 ].nativeElement.click(); + radios[1].nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -299,8 +307,15 @@ describe('radio', () => { @Component({ selector: 'nz-test-radio-single', template: ` - ` + + ` }) export class NzTestRadioSingleComponent { @ViewChild(NzRadioComponent) nzRadioComponent: NzRadioComponent; @@ -313,25 +328,30 @@ export class NzTestRadioSingleComponent { @Component({ selector: 'nz-test-radio-button', template: ` - ` + + ` }) -export class NzTestRadioButtonComponent { -} +export class NzTestRadioButtonComponent {} @Component({ selector: 'nz-test-radio-group', template: ` - + - ` + + ` }) - export class NzTestRadioGroupComponent { size = 'default'; value = 'A'; @@ -353,7 +373,7 @@ export class NzTestRadioFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - radio: [ false ] + radio: [false] }); } @@ -380,7 +400,7 @@ export class NzTestRadioGroupFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - radioGroup: [ 'B' ] + radioGroup: ['B'] }); } @@ -400,9 +420,9 @@ export class NzTestRadioGroupFormComponent { - ` + + ` }) - export class NzTestRadioGroupDisabledComponent { size = 'default'; value = 'A'; @@ -417,20 +437,20 @@ export class NzTestRadioGroupDisabledComponent { template: `
    - + -
    ` + + ` }) export class NzTestRadioGroupDisabledFormComponent implements OnInit { validateForm: FormGroup; - radioValues = [ 'A', 'B', 'C', 'D' ]; + radioValues = ['A', 'B', 'C', 'D']; - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.validateForm = this.fb.group({ - radio: [ { value: 'B', disabled: true } ] + radio: [{ value: 'B', disabled: true }] }); } } @@ -443,7 +463,8 @@ export class NzTestRadioGroupDisabledFormComponent implements OnInit { - ` + + ` }) export class NzTestRadioGroupSolidComponent { value = 'A'; diff --git a/components/rate/demo/basic.ts b/components/rate/demo/basic.ts index 76facb7d230..dab743f417f 100644 --- a/components/rate/demo/basic.ts +++ b/components/rate/demo/basic.ts @@ -2,7 +2,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-rate-basic', - template: ``, + template: ` + + ` }) -export class NzDemoRateBasicComponent { -} +export class NzDemoRateBasicComponent {} diff --git a/components/rate/demo/character.ts b/components/rate/demo/character.ts index e5112ac46b9..740effa1c27 100644 --- a/components/rate/demo/character.ts +++ b/components/rate/demo/character.ts @@ -4,21 +4,20 @@ import { Component } from '@angular/core'; selector: 'nz-demo-rate-character', template: ` -
    +
    -
    +
    A `, - styles : [ - ` + styles: [ + ` .large ::ng-deep .ant-rate-star { font-size: 36px; } ` ] }) -export class NzDemoRateCharacterComponent { -} +export class NzDemoRateCharacterComponent {} diff --git a/components/rate/demo/clear.ts b/components/rate/demo/clear.ts index e46c80fe5c3..c34a6eddb6b 100644 --- a/components/rate/demo/clear.ts +++ b/components/rate/demo/clear.ts @@ -5,7 +5,7 @@ import { Component } from '@angular/core'; template: ` allowClear: true -
    +
    allowClear: false ` diff --git a/components/rate/demo/disabled.ts b/components/rate/demo/disabled.ts index 279a1ef07bc..13a5f716cf7 100644 --- a/components/rate/demo/disabled.ts +++ b/components/rate/demo/disabled.ts @@ -3,8 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-rate-disabled', template: ` - `, - styles : [] + + `, + styles: [] }) -export class NzDemoRateDisabledComponent { -} +export class NzDemoRateDisabledComponent {} diff --git a/components/rate/demo/half.ts b/components/rate/demo/half.ts index d6f809c9d5a..3338d2233ed 100644 --- a/components/rate/demo/half.ts +++ b/components/rate/demo/half.ts @@ -2,7 +2,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-rate-half', - template: `` + template: ` + + ` }) -export class NzDemoRateHalfComponent { -} +export class NzDemoRateHalfComponent {} diff --git a/components/rate/demo/text.ts b/components/rate/demo/text.ts index ea5a30fdea0..cf865202224 100644 --- a/components/rate/demo/text.ts +++ b/components/rate/demo/text.ts @@ -4,10 +4,10 @@ import { Component } from '@angular/core'; selector: 'nz-demo-rate-text', template: ` - {{ value ? tooltips[ value - 1 ] : '' }} + {{ value ? tooltips[value - 1] : '' }} ` }) export class NzDemoRateTextComponent { - tooltips = [ 'terrible', 'bad', 'normal', 'good', 'wonderful' ]; + tooltips = ['terrible', 'bad', 'normal', 'good', 'wonderful']; value = 3; } diff --git a/components/rate/nz-rate-item.component.ts b/components/rate/nz-rate-item.component.ts index 0428a6502aa..4cac960900c 100644 --- a/components/rate/nz-rate-item.component.ts +++ b/components/rate/nz-rate-item.component.ts @@ -1,10 +1,18 @@ -import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, TemplateRef, ViewEncapsulation } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + EventEmitter, + Input, + Output, + TemplateRef, + ViewEncapsulation +} from '@angular/core'; import { InputBoolean } from '../core/util'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, - selector : '[nz-rate-item]', + selector: '[nz-rate-item]', templateUrl: './nz-rate-item.component.html' }) export class NzRateItemComponent { diff --git a/components/rate/nz-rate.component.ts b/components/rate/nz-rate.component.ts index 7ddb6359144..3e22735eb7b 100644 --- a/components/rate/nz-rate.component.ts +++ b/components/rate/nz-rate.component.ts @@ -23,16 +23,16 @@ import { NgClassType } from '../core/types/ng-class'; import { InputBoolean } from '../core/util/convert'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-rate', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-rate', preserveWhitespaces: false, - templateUrl : './nz-rate.component.html', - providers : [ + templateUrl: './nz-rate.component.html', + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzRateComponent), - multi : true + multi: true } ] }) @@ -75,7 +75,9 @@ export class NzRateComponent implements OnInit, ControlValueAccessor, AfterViewI return this._count; } - get nzValue(): number { return this._value; } + get nzValue(): number { + return this._value; + } set nzValue(input: number) { if (this._value === input) { @@ -87,8 +89,7 @@ export class NzRateComponent implements OnInit, ControlValueAccessor, AfterViewI this.hoverValue = Math.ceil(input); } - constructor(private renderer: Renderer2, private cdr: ChangeDetectorRef) { - } + constructor(private renderer: Renderer2, private cdr: ChangeDetectorRef) {} ngOnChanges(changes: SimpleChanges): void { if (changes.nzAutoFocus && !changes.nzAutoFocus.isFirstChange()) { @@ -129,8 +130,7 @@ export class NzRateComponent implements OnInit, ControlValueAccessor, AfterViewI } onItemHover(index: number, isHalf: boolean): void { - if (this.nzDisabled || - (this.hoverValue === index + 1 && isHalf === this.hasHalf)) { + if (this.nzDisabled || (this.hoverValue === index + 1 && isHalf === this.hasHalf)) { return; } @@ -165,9 +165,9 @@ export class NzRateComponent implements OnInit, ControlValueAccessor, AfterViewI onKeyDown(e: KeyboardEvent): void { const oldVal = this.nzValue; - if (e.keyCode === RIGHT_ARROW && (this.nzValue < this.nzCount)) { + if (e.keyCode === RIGHT_ARROW && this.nzValue < this.nzCount) { this.nzValue += this.nzAllowHalf ? 0.5 : 1; - } else if (e.keyCode === LEFT_ARROW && (this.nzValue > 0)) { + } else if (e.keyCode === LEFT_ARROW && this.nzValue > 0) { this.nzValue -= this.nzAllowHalf ? 0.5 : 1; } @@ -180,16 +180,18 @@ export class NzRateComponent implements OnInit, ControlValueAccessor, AfterViewI setClasses(i: number): object { return { - [ `${this.innerPrefixCls}-full` ] : (i + 1 < this.hoverValue) || (!this.hasHalf) && (i + 1 === this.hoverValue), - [ `${this.innerPrefixCls}-half` ] : (this.hasHalf) && (i + 1 === this.hoverValue), - [ `${this.innerPrefixCls}-active` ] : (this.hasHalf) && (i + 1 === this.hoverValue), - [ `${this.innerPrefixCls}-zero` ] : (i + 1 > this.hoverValue), - [ `${this.innerPrefixCls}-focused` ]: (this.hasHalf) && (i + 1 === this.hoverValue) && this.isFocused + [`${this.innerPrefixCls}-full`]: i + 1 < this.hoverValue || (!this.hasHalf && i + 1 === this.hoverValue), + [`${this.innerPrefixCls}-half`]: this.hasHalf && i + 1 === this.hoverValue, + [`${this.innerPrefixCls}-active`]: this.hasHalf && i + 1 === this.hoverValue, + [`${this.innerPrefixCls}-zero`]: i + 1 > this.hoverValue, + [`${this.innerPrefixCls}-focused`]: this.hasHalf && i + 1 === this.hoverValue && this.isFocused }; } private updateStarArray(): void { - this.starArray = Array(this.nzCount).fill(0).map((_, i) => i); + this.starArray = Array(this.nzCount) + .fill(0) + .map((_, i) => i); } // #region Implement `ControlValueAccessor` diff --git a/components/rate/nz-rate.module.ts b/components/rate/nz-rate.module.ts index 3672d82bff0..2baa329061f 100644 --- a/components/rate/nz-rate.module.ts +++ b/components/rate/nz-rate.module.ts @@ -8,9 +8,8 @@ import { NzRateItemComponent } from './nz-rate-item.component'; import { NzRateComponent } from './nz-rate.component'; @NgModule({ - exports : [ NzRateComponent ], - declarations: [ NzRateComponent, NzRateItemComponent ], - imports : [ CommonModule, NzIconModule, NzToolTipModule ] + exports: [NzRateComponent], + declarations: [NzRateComponent, NzRateItemComponent], + imports: [CommonModule, NzIconModule, NzToolTipModule] }) -export class NzRateModule { -} +export class NzRateModule {} diff --git a/components/rate/nz-rate.spec.ts b/components/rate/nz-rate.spec.ts index 615ce454baf..2912e885d98 100644 --- a/components/rate/nz-rate.spec.ts +++ b/components/rate/nz-rate.spec.ts @@ -12,8 +12,8 @@ import { NzRateModule } from './nz-rate.module'; describe('rate', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzRateModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestRateBasicComponent, NzTestRateFormComponent ] + imports: [NzRateModule, FormsModule, ReactiveFormsModule], + declarations: [NzTestRateBasicComponent, NzTestRateFormComponent] }); TestBed.compileComponents(); })); @@ -47,7 +47,7 @@ describe('rate', () => { it('should click work', fakeAsync(() => { fixture.detectChanges(); expect(testComponent.value).toBe(0); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -58,7 +58,7 @@ describe('rate', () => { testComponent.allowHalf = true; fixture.detectChanges(); expect(testComponent.value).toBe(0); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.children[ 1 ].click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.children[1].click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -69,13 +69,13 @@ describe('rate', () => { testComponent.allowClear = false; fixture.detectChanges(); expect(testComponent.value).toBe(0); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(testComponent.value).toBe(4); expect(testComponent.modelChange).toHaveBeenCalledTimes(1); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -83,7 +83,7 @@ describe('rate', () => { expect(testComponent.modelChange).toHaveBeenCalledTimes(1); testComponent.allowClear = true; fixture.detectChanges(); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -94,7 +94,7 @@ describe('rate', () => { testComponent.disabled = true; fixture.detectChanges(); expect(testComponent.value).toBe(0); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -105,7 +105,7 @@ describe('rate', () => { fixture.detectChanges(); expect(rate.nativeElement.firstElementChild.children.length).toBe(5); expect(testComponent.value).toBe(0); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); @@ -140,20 +140,23 @@ describe('rate', () => { }); it('should hover rate work', () => { fixture.detectChanges(); - dispatchFakeEvent(rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild, 'mouseover'); + dispatchFakeEvent( + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild, + 'mouseover' + ); fixture.detectChanges(); - expect(rate.nativeElement.firstElementChild.children[ 3 ].classList).toContain('ant-rate-star-full'); + expect(rate.nativeElement.firstElementChild.children[3].classList).toContain('ant-rate-star-full'); expect(testComponent.onHoverChange).toHaveBeenCalledWith(4); expect(testComponent.onHoverChange).toHaveBeenCalledTimes(1); - dispatchFakeEvent(rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild, 'mouseover'); + dispatchFakeEvent(rate.nativeElement.firstElementChild.children[3].firstElementChild, 'mouseover'); fixture.detectChanges(); expect(testComponent.onHoverChange).toHaveBeenCalledTimes(1); dispatchFakeEvent(rate.nativeElement.firstElementChild, 'mouseleave'); fixture.detectChanges(); - expect(rate.nativeElement.firstElementChild.children[ 3 ].classList).toContain('ant-rate-star-zero'); + expect(rate.nativeElement.firstElementChild.children[3].classList).toContain('ant-rate-star-zero'); testComponent.disabled = true; fixture.detectChanges(); - dispatchFakeEvent(rate.nativeElement.firstElementChild.children[ 2 ].firstElementChild, 'mouseover'); + dispatchFakeEvent(rate.nativeElement.firstElementChild.children[2].firstElementChild, 'mouseover'); expect(testComponent.onHoverChange).toHaveBeenCalledTimes(1); }); it('should keydown work', () => { @@ -215,7 +218,7 @@ describe('rate', () => { it('should set disabled work', fakeAsync(() => { flush(); expect(testComponent.formGroup.get('rate')!.value).toBe(1); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); expect(testComponent.formGroup.get('rate')!.value).toBe(4); fixture.detectChanges(); @@ -226,7 +229,7 @@ describe('rate', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - rate.nativeElement.firstElementChild.children[ 3 ].firstElementChild.firstElementChild.click(); + rate.nativeElement.firstElementChild.children[3].firstElementChild.firstElementChild.click(); fixture.detectChanges(); expect(testComponent.formGroup.get('rate')!.value).toBe(2); })); @@ -247,8 +250,10 @@ describe('rate', () => { [nzAllowHalf]="allowHalf" [nzAllowClear]="allowClear" [nzDisabled]="disabled" - [nzAutoFocus]="autoFocus"> - ` + [nzAutoFocus]="autoFocus" + > + + ` }) export class NzTestRateBasicComponent { @ViewChild(NzRateComponent) nzRateComponent: NzRateComponent; @@ -278,7 +283,7 @@ export class NzTestRateFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - rate: [ 1 ] + rate: [1] }); } diff --git a/components/select/demo/automatic-tokenization.ts b/components/select/demo/automatic-tokenization.ts index 63996d8f092..4c8eaa7c90e 100644 --- a/components/select/demo/automatic-tokenization.ts +++ b/components/select/demo/automatic-tokenization.ts @@ -4,17 +4,16 @@ import { Component, OnInit } from '@angular/core'; selector: 'nz-demo-select-automatic-tokenization', template: ` - - + ` }) export class NzDemoSelectAutomaticTokenizationComponent implements OnInit { - listOfOption: Array<{ label: string, value: string }> = []; + listOfOption: Array<{ label: string; value: string }> = []; listOfTagOptions = []; ngOnInit(): void { - const children: Array<{ label: string, value: string }> = []; + const children: Array<{ label: string; value: string }> = []; for (let i = 10; i < 36; i++) { children.push({ label: i.toString(36) + i, value: i.toString(36) + i }); } diff --git a/components/select/demo/basic.ts b/components/select/demo/basic.ts index f49f831c27d..3dd320c0ca1 100644 --- a/components/select/demo/basic.ts +++ b/components/select/demo/basic.ts @@ -17,7 +17,7 @@ import { Component } from '@angular/core';
    `, - styles : [ + styles: [ ` nz-select { margin-right: 8px; diff --git a/components/select/demo/coordinate.ts b/components/select/demo/coordinate.ts index 3899994c2bc..579e0414f2e 100644 --- a/components/select/demo/coordinate.ts +++ b/components/select/demo/coordinate.ts @@ -12,7 +12,7 @@ import { Component } from '@angular/core';
    `, - styles : [ + styles: [ ` nz-select { margin-right: 8px; @@ -23,13 +23,13 @@ import { Component } from '@angular/core'; export class NzDemoSelectCoordinateComponent { selectedProvince = 'Zhejiang'; selectedCity = 'Hangzhou'; - provinceData = [ 'Zhejiang', 'Jiangsu' ]; - cityData: { [ place: string]: string[] } = { - Zhejiang: [ 'Hangzhou', 'Ningbo', 'Wenzhou' ], - Jiangsu : [ 'Nanjing', 'Suzhou', 'Zhenjiang' ] + provinceData = ['Zhejiang', 'Jiangsu']; + cityData: { [place: string]: string[] } = { + Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'], + Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'] }; provinceChange(value: string): void { - this.selectedCity = this.cityData[ value ][ 0 ]; + this.selectedCity = this.cityData[value][0]; } } diff --git a/components/select/demo/custom-dropdown-menu.ts b/components/select/demo/custom-dropdown-menu.ts index 861f5030dac..06406307a7e 100644 --- a/components/select/demo/custom-dropdown-menu.ts +++ b/components/select/demo/custom-dropdown-menu.ts @@ -9,11 +9,8 @@ import { Component } from '@angular/core'; -
    - Add item -
    +
    Add item
    ` }) -export class NzDemoSelectCustomDropdownMenuComponent { -} +export class NzDemoSelectCustomDropdownMenuComponent {} diff --git a/components/select/demo/hide-selected.ts b/components/select/demo/hide-selected.ts index 0f99967fccb..09b1ba9ac6c 100644 --- a/components/select/demo/hide-selected.ts +++ b/components/select/demo/hide-selected.ts @@ -3,7 +3,12 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-select-hide-selected', template: ` - + @@ -11,7 +16,7 @@ import { Component } from '@angular/core'; ` }) export class NzDemoSelectHideSelectedComponent { - listOfOption = [ 'Apples', 'Nails', 'Bananas', 'Helicopters' ]; + listOfOption = ['Apples', 'Nails', 'Bananas', 'Helicopters']; listOfSelectedValue: string[] = []; isNotSelected(value: string): boolean { diff --git a/components/select/demo/label-in-value.ts b/components/select/demo/label-in-value.ts index f7364727697..dc5ade01df4 100644 --- a/components/select/demo/label-in-value.ts +++ b/components/select/demo/label-in-value.ts @@ -3,23 +3,27 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-select-label-in-value', template: ` -

    The selected option's age is {{selectedValue?.age}}

    -
    - +

    The selected option's age is {{ selectedValue?.age }}

    +
    + ` }) export class NzDemoSelectLabelInValueComponent { - optionList = [ - { label: 'Lucy', value: 'lucy', age: 20 }, - { label: 'Jack', value: 'jack', age: 22 } - ]; + optionList = [{ label: 'Lucy', value: 'lucy', age: 20 }, { label: 'Jack', value: 'jack', age: 22 }]; selectedValue = { label: 'Jack', value: 'jack', age: 22 }; // tslint:disable-next-line:no-any - compareFn = (o1: any, o2: any) => o1 && o2 ? o1.value === o2.value : o1 === o2; + compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.value === o2.value : o1 === o2); - log(value: { label: string, value: string, age: number }): void { + log(value: { label: string; value: string; age: number }): void { console.log(value); } } diff --git a/components/select/demo/multiple.ts b/components/select/demo/multiple.ts index 8771b6b4c82..dbe9ba6ee4f 100644 --- a/components/select/demo/multiple.ts +++ b/components/select/demo/multiple.ts @@ -3,20 +3,25 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-select-multiple', template: ` - + - - and {{selectedList.length}} more selected - + and {{ selectedList.length }} more selected ` }) export class NzDemoSelectMultipleComponent implements OnInit { - listOfOption: Array<{ label: string, value: string }> = []; - listOfSelectedValue = [ 'a10', 'c12' ]; + listOfOption: Array<{ label: string; value: string }> = []; + listOfSelectedValue = ['a10', 'c12']; ngOnInit(): void { - const children: Array<{ label: string, value: string }> = []; + const children: Array<{ label: string; value: string }> = []; for (let i = 10; i < 36; i++) { children.push({ label: i.toString(36) + i, value: i.toString(36) + i }); } diff --git a/components/select/demo/scroll-load.ts b/components/select/demo/scroll-load.ts index 008785bb3ed..a2e05416c0d 100644 --- a/components/select/demo/scroll-load.ts +++ b/components/select/demo/scroll-load.ts @@ -6,18 +6,26 @@ import { map } from 'rxjs/operators'; @Component({ selector: 'nz-demo-select-scroll-load', template: ` - + Loading Data... `, - styles : [ ` - .loading-icon { - margin-right: 8px; - } - ` ] + styles: [ + ` + .loading-icon { + margin-right: 8px; + } + ` + ] }) export class NzDemoSelectScrollLoadComponent implements OnInit { randomUserUrl = 'https://api.randomuser.me/?results=10'; @@ -25,21 +33,25 @@ export class NzDemoSelectScrollLoadComponent implements OnInit { selectedUser = ''; isLoading = false; // tslint:disable:no-any - getRandomNameList: Observable = this.http.get(`${this.randomUserUrl}`).pipe(map((res: any) => res.results)).pipe(map((list: any) => { - return list.map((item: any) => `${item.name.first}`); - })); + getRandomNameList: Observable = this.http + .get(`${this.randomUserUrl}`) + .pipe(map((res: any) => res.results)) + .pipe( + map((list: any) => { + return list.map((item: any) => `${item.name.first}`); + }) + ); // tslint:enable:no-any loadMore(): void { this.isLoading = true; this.getRandomNameList.subscribe(data => { this.isLoading = false; - this.optionList = [ ...this.optionList, ...data ]; + this.optionList = [...this.optionList, ...data]; }); } - constructor(private http: HttpClient) { - } + constructor(private http: HttpClient) {} ngOnInit(): void { this.loadMore(); diff --git a/components/select/demo/search-box.ts b/components/select/demo/search-box.ts index 6f562c24056..f8276f2b2d8 100644 --- a/components/select/demo/search-box.ts +++ b/components/select/demo/search-box.ts @@ -12,32 +12,31 @@ import { Component } from '@angular/core'; [nzShowArrow]="false" [nzFilterOption]="nzFilterOption" [(ngModel)]="selectedValue" - (nzOnSearch)="search($event)"> - - + (nzOnSearch)="search($event)" + > + ` }) export class NzDemoSelectSearchBoxComponent { selectedValue = ''; - listOfOption: Array<{ value: string, text: string }> = []; + listOfOption: Array<{ value: string; text: string }> = []; nzFilterOption = () => true; - constructor(private httpClient: HttpClient) { - } + constructor(private httpClient: HttpClient) {} search(value: string): void { - this.httpClient.jsonp<{ result: Array<[ string, string ]> }>(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, 'callback').subscribe(data => { - const listOfOption: Array<{ value: string, text: string }> = []; - data.result.forEach(item => { - listOfOption.push({ - value: item[ 0 ], - text : item[ 0 ] + this.httpClient + .jsonp<{ result: Array<[string, string]> }>(`https://suggest.taobao.com/sug?code=utf-8&q=${value}`, 'callback') + .subscribe(data => { + const listOfOption: Array<{ value: string; text: string }> = []; + data.result.forEach(item => { + listOfOption.push({ + value: item[0], + text: item[0] + }); }); + this.listOfOption = listOfOption; }); - this.listOfOption = listOfOption; - }); } } diff --git a/components/select/demo/search.ts b/components/select/demo/search.ts index c55397c5113..030ca175b19 100644 --- a/components/select/demo/search.ts +++ b/components/select/demo/search.ts @@ -3,7 +3,13 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-select-search', template: ` - + diff --git a/components/select/demo/select-users.ts b/components/select/demo/select-users.ts index fb9ced183b6..9ad830a11b6 100644 --- a/components/select/demo/select-users.ts +++ b/components/select/demo/select-users.ts @@ -6,7 +6,16 @@ import { debounceTime, map, switchMap } from 'rxjs/operators'; @Component({ selector: 'nz-demo-select-select-users', template: ` - + @@ -15,11 +24,13 @@ import { debounceTime, map, switchMap } from 'rxjs/operators'; `, - styles : [ ` - .loading-icon { - margin-right: 8px; - } - ` ] + styles: [ + ` + .loading-icon { + margin-right: 8px; + } + ` + ] }) export class NzDemoSelectSelectUsersComponent implements OnInit { randomUserUrl = 'https://api.randomuser.me/?results=5'; @@ -33,15 +44,23 @@ export class NzDemoSelectSelectUsersComponent implements OnInit { this.searchChange$.next(value); } - constructor(private http: HttpClient) { - } + constructor(private http: HttpClient) {} ngOnInit(): void { // tslint:disable-next-line:no-any - const getRandomNameList = (name: string) => this.http.get(`${this.randomUserUrl}`).pipe(map((res: any) => res.results)).pipe(map((list: any) => { - return list.map((item: any) => `${item.name.first} ${name}`); - })); - const optionList$: Observable = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(getRandomNameList)); + const getRandomNameList = (name: string) => + this.http + .get(`${this.randomUserUrl}`) + .pipe(map((res: any) => res.results)) + .pipe( + map((list: any) => { + return list.map((item: any) => `${item.name.first} ${name}`); + }) + ); + const optionList$: Observable = this.searchChange$ + .asObservable() + .pipe(debounceTime(500)) + .pipe(switchMap(getRandomNameList)); optionList$.subscribe(data => { this.optionList = data; this.isLoading = false; diff --git a/components/select/demo/size.ts b/components/select/demo/size.ts index 24d00895322..dfcd4296f04 100644 --- a/components/select/demo/size.ts +++ b/components/select/demo/size.ts @@ -8,33 +8,39 @@ import { Component, OnInit } from '@angular/core'; -

    +

    -

    +

    -

    - +

    + -

    +

    ` }) export class NzDemoSelectSizeComponent implements OnInit { - listOfOption: Array<{ label: string, value: string }> = []; + listOfOption: Array<{ label: string; value: string }> = []; size = 'default'; singleValue = 'a10'; - multipleValue = [ 'a10', 'c12' ]; - tagValue = [ 'a10', 'c12', 'tag' ]; + multipleValue = ['a10', 'c12']; + tagValue = ['a10', 'c12', 'tag']; ngOnInit(): void { - const children: Array<{ label: string, value: string }> = []; + const children: Array<{ label: string; value: string }> = []; for (let i = 10; i < 36; i++) { children.push({ label: i.toString(36) + i, value: i.toString(36) + i }); } diff --git a/components/select/demo/tags.ts b/components/select/demo/tags.ts index 7327cf6fe36..a99198748dc 100644 --- a/components/select/demo/tags.ts +++ b/components/select/demo/tags.ts @@ -4,17 +4,16 @@ import { Component, OnInit } from '@angular/core'; selector: 'nz-demo-select-tags', template: ` - - + ` }) export class NzDemoSelectTagsComponent implements OnInit { - listOfOption: Array<{ label: string, value: string }> = []; + listOfOption: Array<{ label: string; value: string }> = []; listOfTagOptions = []; ngOnInit(): void { - const children: Array<{ label: string, value: string }> = []; + const children: Array<{ label: string; value: string }> = []; for (let i = 10; i < 36; i++) { children.push({ label: i.toString(36) + i, value: i.toString(36) + i }); } diff --git a/components/select/nz-option-container.component.ts b/components/select/nz-option-container.component.ts index 1ccf2fb14e0..ed75b41b080 100644 --- a/components/select/nz-option-container.component.ts +++ b/components/select/nz-option-container.component.ts @@ -23,11 +23,11 @@ import { NzOptionComponent } from './nz-option.component'; import { NzSelectService } from './nz-select.service'; @Component({ - selector : '[nz-option-container]', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + selector: '[nz-option-container]', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - templateUrl : './nz-option-container.component.html' + templateUrl: './nz-option-container.component.html' }) export class NzOptionContainerComponent implements OnDestroy, OnInit { private destroy$ = new Subject(); @@ -41,8 +41,8 @@ export class NzOptionContainerComponent implements OnDestroy, OnInit { // delay after open setTimeout(() => { if (this.listOfNzOptionLiComponent && this.listOfNzOptionLiComponent.length && option) { - const targetOption = this.listOfNzOptionLiComponent.find( - o => this.nzSelectService.compareWith(o.nzOption.nzValue, option.nzValue) + const targetOption = this.listOfNzOptionLiComponent.find(o => + this.nzSelectService.compareWith(o.nzOption.nzValue, option.nzValue) ); /* tslint:disable:no-any */ if (targetOption && targetOption.el && (targetOption.el as any).scrollIntoViewIfNeeded) { @@ -62,33 +62,28 @@ export class NzOptionContainerComponent implements OnDestroy, OnInit { return option.nzValue; } - constructor(public nzSelectService: NzSelectService, private cdr: ChangeDetectorRef, private ngZone: NgZone) { - } + constructor(public nzSelectService: NzSelectService, private cdr: ChangeDetectorRef, private ngZone: NgZone) {} ngOnInit(): void { - this.nzSelectService.activatedOption$.pipe( - takeUntil(this.destroy$) - ).subscribe((option) => { + this.nzSelectService.activatedOption$.pipe(takeUntil(this.destroy$)).subscribe(option => { this.scrollIntoViewIfNeeded(option!); }); - this.nzSelectService.check$.pipe( - takeUntil(this.destroy$) - ).subscribe(() => { + this.nzSelectService.check$.pipe(takeUntil(this.destroy$)).subscribe(() => { this.cdr.markForCheck(); }); this.ngZone.runOutsideAngular(() => { const ul = this.dropdownUl.nativeElement; - fromEvent(ul, 'scroll').pipe( - takeUntil(this.destroy$) - ).subscribe(e => { - e.preventDefault(); - e.stopPropagation(); - if (ul && (ul.scrollHeight < (ul.clientHeight + ul.scrollTop + 10))) { - this.ngZone.run(() => { - this.nzScrollToBottom.emit(); - }); - } - }); + fromEvent(ul, 'scroll') + .pipe(takeUntil(this.destroy$)) + .subscribe(e => { + e.preventDefault(); + e.stopPropagation(); + if (ul && ul.scrollHeight < ul.clientHeight + ul.scrollTop + 10) { + this.ngZone.run(() => { + this.nzScrollToBottom.emit(); + }); + } + }); }); } diff --git a/components/select/nz-option-container.spec.ts b/components/select/nz-option-container.spec.ts index 74e3e6a400a..aad883430ec 100644 --- a/components/select/nz-option-container.spec.ts +++ b/components/select/nz-option-container.spec.ts @@ -39,20 +39,20 @@ describe('nz-select option container', () => { beforeEach(fakeAsync(() => { let nzSelectServiceStub: Partial; nzSelectServiceStub = { - searchValue : '', - filterOption : defaultFilterOption, - serverSearch : false, - listOfNzOptionComponent : createListOfOption(20), - check$ : new Subject(), - activatedOption$ : new ReplaySubject(1), + searchValue: '', + filterOption: defaultFilterOption, + serverSearch: false, + listOfNzOptionComponent: createListOfOption(20), + check$: new Subject(), + activatedOption$: new ReplaySubject(1), listOfNzOptionGroupComponent: createListOfGroupOption(10, 10), - listOfSelectedValue$ : new Subject(), - compareWith : (o1, o2) => o1 === o2 + listOfSelectedValue$: new Subject(), + compareWith: (o1, o2) => o1 === o2 }; TestBed.configureTestingModule({ - imports : [ NzSelectModule, NoopAnimationsModule ], - providers : [ { provide: NzSelectService, useValue: nzSelectServiceStub } ], - declarations: [ NzOptionContainerSpecComponent ] + imports: [NzSelectModule, NoopAnimationsModule], + providers: [{ provide: NzSelectService, useValue: nzSelectServiceStub }], + declarations: [NzOptionContainerSpecComponent] }); TestBed.compileComponents(); })); @@ -79,7 +79,9 @@ describe('nz-select option container', () => { it('should scrollIntoViewIfNeeded', fakeAsync(() => { fixture.detectChanges(); const nzSelectService = fixture.debugElement.injector.get(NzSelectService); - nzSelectService.activatedOption$.next(nzSelectService.listOfNzOptionComponent[ nzSelectService.listOfNzOptionComponent.length - 1 ]); + nzSelectService.activatedOption$.next( + nzSelectService.listOfNzOptionComponent[nzSelectService.listOfNzOptionComponent.length - 1] + ); fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -106,20 +108,18 @@ describe('nz-select option container', () => { }); @Component({ - template : ` -
    -
    + template: ` +
    icon `, encapsulation: ViewEncapsulation.None, - styleUrls : [ - '../style/index.less', - './style/index.less' - ] + styleUrls: ['../style/index.less', './style/index.less'] }) export class NzOptionContainerSpecComponent { destroy = false; diff --git a/components/select/nz-option-group.component.ts b/components/select/nz-option-group.component.ts index c9f7700f0c3..7653e3b604c 100644 --- a/components/select/nz-option-group.component.ts +++ b/components/select/nz-option-group.component.ts @@ -10,10 +10,10 @@ import { import { NzOptionComponent } from './nz-option.component'; @Component({ - selector : 'nz-option-group', - encapsulation : ViewEncapsulation.None, + selector: 'nz-option-group', + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl : './nz-option-group.component.html' + templateUrl: './nz-option-group.component.html' }) export class NzOptionGroupComponent { isLabelString = false; diff --git a/components/select/nz-option-li.component.ts b/components/select/nz-option-li.component.ts index dec4cf38976..9461608b152 100644 --- a/components/select/nz-option-li.component.ts +++ b/components/select/nz-option-li.component.ts @@ -1,9 +1,13 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, - Input, OnDestroy, - OnInit, Renderer2, TemplateRef, + Component, + ElementRef, + Input, + OnDestroy, + OnInit, + Renderer2, + TemplateRef, ViewEncapsulation } from '@angular/core'; import { Subject } from 'rxjs'; @@ -13,18 +17,18 @@ import { NzOptionComponent } from './nz-option.component'; import { NzSelectService } from './nz-select.service'; @Component({ - selector : '[nz-option-li]', - templateUrl : './nz-option-li.component.html', + selector: '[nz-option-li]', + templateUrl: './nz-option-li.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - host : { + encapsulation: ViewEncapsulation.None, + host: { '[class.ant-select-dropdown-menu-item-selected]': 'selected && !nzOption.nzDisabled', '[class.ant-select-dropdown-menu-item-disabled]': 'nzOption.nzDisabled', - '[class.ant-select-dropdown-menu-item-active]' : 'active && !nzOption.nzDisabled', - '[attr.unselectable]' : '"unselectable"', - '[style.user-select]' : '"none"', - '(click)' : 'clickOption()', - '(mousedown)' : '$event.preventDefault()' + '[class.ant-select-dropdown-menu-item-active]': 'active && !nzOption.nzDisabled', + '[attr.unselectable]': '"unselectable"', + '[style.user-select]': '"none"', + '(click)': 'clickOption()', + '(mousedown)': '$event.preventDefault()' } }) export class NzOptionLiComponent implements OnInit, OnDestroy { @@ -39,20 +43,21 @@ export class NzOptionLiComponent implements OnInit, OnDestroy { this.nzSelectService.clickOption(this.nzOption); } - constructor(private elementRef: ElementRef, public nzSelectService: NzSelectService, private cdr: ChangeDetectorRef, renderer: Renderer2) { + constructor( + private elementRef: ElementRef, + public nzSelectService: NzSelectService, + private cdr: ChangeDetectorRef, + renderer: Renderer2 + ) { renderer.addClass(elementRef.nativeElement, 'ant-select-dropdown-menu-item'); } ngOnInit(): void { - this.nzSelectService.listOfSelectedValue$.pipe( - takeUntil(this.destroy$) - ).subscribe(list => { + this.nzSelectService.listOfSelectedValue$.pipe(takeUntil(this.destroy$)).subscribe(list => { this.selected = isNotNil(list.find(v => this.nzSelectService.compareWith(v, this.nzOption.nzValue))); this.cdr.markForCheck(); }); - this.nzSelectService.activatedOption$.pipe( - takeUntil(this.destroy$) - ).subscribe(option => { + this.nzSelectService.activatedOption$.pipe(takeUntil(this.destroy$)).subscribe(option => { if (option) { this.active = this.nzSelectService.compareWith(option.nzValue, this.nzOption.nzValue); } else { diff --git a/components/select/nz-option-li.spec.ts b/components/select/nz-option-li.spec.ts index 003b47ebd63..f10b9aa06c7 100644 --- a/components/select/nz-option-li.spec.ts +++ b/components/select/nz-option-li.spec.ts @@ -11,15 +11,14 @@ describe('select option li', () => { beforeEach(fakeAsync(() => { let nzSelectServiceStub: Partial; nzSelectServiceStub = { - activatedOption$ : new ReplaySubject(1), + activatedOption$: new ReplaySubject(1), listOfSelectedValue$: new Subject(), - compareWith : (o1, o2) => o1 === o2, - clickOption : () => { - } + compareWith: (o1, o2) => o1 === o2, + clickOption: () => {} }; TestBed.configureTestingModule({ - providers : [ { provide: NzSelectService, useValue: nzSelectServiceStub } ], - declarations: [ NzTestSelectOptionLiComponent, NzOptionLiComponent ] + providers: [{ provide: NzSelectService, useValue: nzSelectServiceStub }], + declarations: [NzTestSelectOptionLiComponent, NzOptionLiComponent] }); TestBed.compileComponents(); })); @@ -41,11 +40,11 @@ describe('select option li', () => { fixture.detectChanges(); expect(liComponent.selected).toBe(false); // @ts-ignore - nzSelectService.listOfSelectedValue$.next([ '01_value' ]); + nzSelectService.listOfSelectedValue$.next(['01_value']); fixture.detectChanges(); expect(liComponent.selected).toBe(true); // @ts-ignore - nzSelectService.listOfSelectedValue$.next([ '01_label' ]); + nzSelectService.listOfSelectedValue$.next(['01_label']); fixture.detectChanges(); expect(liComponent.selected).toBe(false); }); @@ -68,13 +67,13 @@ describe('select option li', () => { const checkSpy = spyOn(liComponent.cdr, 'markForCheck'); expect(checkSpy).toHaveBeenCalledTimes(0); // @ts-ignore - nzSelectService.listOfSelectedValue$.next([ '01_value' ]); + nzSelectService.listOfSelectedValue$.next(['01_value']); fixture.detectChanges(); expect(checkSpy).toHaveBeenCalledTimes(1); testComponent.destroy = true; fixture.detectChanges(); // @ts-ignore - nzSelectService.listOfSelectedValue$.next([ '01_value' ]); + nzSelectService.listOfSelectedValue$.next(['01_value']); fixture.detectChanges(); expect(checkSpy).toHaveBeenCalledTimes(1); }); diff --git a/components/select/nz-option.component.ts b/components/select/nz-option.component.ts index 19eb4945fad..d3b7d0997d2 100644 --- a/components/select/nz-option.component.ts +++ b/components/select/nz-option.component.ts @@ -3,10 +3,10 @@ import { ChangeDetectionStrategy, Component, Input, TemplateRef, ViewChild, View import { InputBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-option', - encapsulation : ViewEncapsulation.None, + selector: 'nz-option', + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - templateUrl : './nz-option.component.html' + templateUrl: './nz-option.component.html' }) export class NzOptionComponent { @ViewChild(TemplateRef) template: TemplateRef; diff --git a/components/select/nz-option.pipe.spec.ts b/components/select/nz-option.pipe.spec.ts index 1126fa30ef5..fe3b9ab4577 100644 --- a/components/select/nz-option.pipe.spec.ts +++ b/components/select/nz-option.pipe.spec.ts @@ -33,7 +33,7 @@ describe('nz-option pipe', () => { }); it('should return correct value with inputValue', () => { const result = pipe.transform(listOfOption, '9', defaultFilterOption, false); - expect(result[ 0 ].nzLabel).toBe('label9'); + expect(result[0].nzLabel).toBe('label9'); expect(result.length).toBe(1); }); it('should return correct value with null option', () => { @@ -49,7 +49,7 @@ describe('nz-option pipe', () => { } }; const result = pipe.transform(listOfOption, '9', filterOption, false); - expect(result[ 0 ].nzLabel).toBe('label8'); + expect(result[0].nzLabel).toBe('label8'); expect(result.length).toBe(1); }); it('should return correct value without inputValue', () => { @@ -67,13 +67,13 @@ describe('nz-option pipe', () => { beforeEach(() => { pipe = new NzFilterGroupOptionPipe(); listOfGroupOption = [ - generateGroupOption('g1', [ generateOption('a', 'a'), generateOption('b', 'b') ]), - generateGroupOption('g2', [ generateOption('b', 'b'), generateOption('c', 'c') ]) + generateGroupOption('g1', [generateOption('a', 'a'), generateOption('b', 'b')]), + generateGroupOption('g2', [generateOption('b', 'b'), generateOption('c', 'c')]) ]; }); it('should return correct value with inputValue', () => { const result01 = pipe.transform(listOfGroupOption, 'a', defaultFilterOption, false); - expect(result01[ 0 ].nzLabel).toBe('g1'); + expect(result01[0].nzLabel).toBe('g1'); expect(result01.length).toBe(1); const result02 = pipe.transform(listOfGroupOption, 'b', defaultFilterOption, false); expect(result02.length).toBe(2); @@ -87,7 +87,7 @@ describe('nz-option pipe', () => { } }; const result = pipe.transform(listOfGroupOption, 'a', filterOption, false); - expect(result[ 0 ].nzLabel).toBe('g2'); + expect(result[0].nzLabel).toBe('g2'); expect(result.length).toBe(1); }); it('should return correct value without inputValue', () => { diff --git a/components/select/nz-option.pipe.ts b/components/select/nz-option.pipe.ts index ce9f419d311..f386ae1270c 100644 --- a/components/select/nz-option.pipe.ts +++ b/components/select/nz-option.pipe.ts @@ -6,7 +6,12 @@ export type TFilterOption = (input: string, option: NzOptionComponent) => boolea @Pipe({ name: 'nzFilterOption' }) export class NzFilterOptionPipe implements PipeTransform { - transform(options: NzOptionComponent[], searchValue: string, filterOption: TFilterOption, serverSearch: boolean): NzOptionComponent[] { + transform( + options: NzOptionComponent[], + searchValue: string, + filterOption: TFilterOption, + serverSearch: boolean + ): NzOptionComponent[] { if (serverSearch || !searchValue) { return options; } else { @@ -17,7 +22,12 @@ export class NzFilterOptionPipe implements PipeTransform { @Pipe({ name: 'nzFilterGroupOption' }) export class NzFilterGroupOptionPipe implements PipeTransform { - transform(groups: NzOptionGroupComponent[], searchValue: string, filterOption: TFilterOption, serverSearch: boolean): NzOptionGroupComponent[] { + transform( + groups: NzOptionGroupComponent[], + searchValue: string, + filterOption: TFilterOption, + serverSearch: boolean + ): NzOptionGroupComponent[] { if (serverSearch || !searchValue) { return groups; } else { diff --git a/components/select/nz-select-top-control.component.ts b/components/select/nz-select-top-control.component.ts index 4bae7f909ca..da71c1a13b5 100644 --- a/components/select/nz-select-top-control.component.ts +++ b/components/select/nz-select-top-control.component.ts @@ -21,12 +21,12 @@ import { NzOptionComponent } from './nz-option.component'; import { NzSelectService } from './nz-select.service'; @Component({ - selector : '[nz-select-top-control]', + selector: '[nz-select-top-control]', preserveWhitespaces: false, - animations : [ zoomMotion ], - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-select-top-control.component.html' + animations: [zoomMotion], + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-select-top-control.component.html' }) export class NzSelectTopControlComponent implements OnInit, OnDestroy { inputValue: string; @@ -66,7 +66,7 @@ export class NzSelectTopControlComponent implements OnInit, OnDestroy { return this.inputValue || this.isComposing || this.nzSelectService.listOfSelectedValue.length ? 'none' : 'block'; } - get selectedValueStyle(): { [ key: string ]: string } { + get selectedValueStyle(): { [key: string]: string } { let showSelectedValue = false; let opacity = 1; if (!this.nzShowSearch) { @@ -95,7 +95,11 @@ export class NzSelectTopControlComponent implements OnInit, OnDestroy { updateWidth(): void { if (this.nzSelectService.isMultipleOrTags && this.inputElement) { if (this.inputValue || this.isComposing) { - this.renderer.setStyle(this.inputElement.nativeElement, 'width', `${this.inputElement.nativeElement.scrollWidth}px`); + this.renderer.setStyle( + this.inputElement.nativeElement, + 'width', + `${this.inputElement.nativeElement.scrollWidth}px` + ); } else { this.renderer.removeStyle(this.inputElement.nativeElement, 'width'); } @@ -107,28 +111,23 @@ export class NzSelectTopControlComponent implements OnInit, OnDestroy { e.stopPropagation(); } - constructor(private renderer: Renderer2, - public nzSelectService: NzSelectService, - private cdr: ChangeDetectorRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + constructor( + private renderer: Renderer2, + public nzSelectService: NzSelectService, + private cdr: ChangeDetectorRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngOnInit(): void { - this.nzSelectService.open$.pipe( - takeUntil(this.destroy$) - ).subscribe(open => { + this.nzSelectService.open$.pipe(takeUntil(this.destroy$)).subscribe(open => { if (this.inputElement && open) { this.inputElement.nativeElement.focus(); } }); - this.nzSelectService.clearInput$.pipe( - takeUntil(this.destroy$) - ).subscribe(() => { + this.nzSelectService.clearInput$.pipe(takeUntil(this.destroy$)).subscribe(() => { this.setInputValue(''); }); - this.nzSelectService.check$.pipe( - takeUntil(this.destroy$) - ).subscribe(() => { + this.nzSelectService.check$.pipe(takeUntil(this.destroy$)).subscribe(() => { this.cdr.markForCheck(); }); } diff --git a/components/select/nz-select-top-control.spec.ts b/components/select/nz-select-top-control.spec.ts index 5bda5a0a6bc..5957cb5d36d 100644 --- a/components/select/nz-select-top-control.spec.ts +++ b/components/select/nz-select-top-control.spec.ts @@ -13,27 +13,23 @@ describe('nz-select top control', () => { beforeEach(fakeAsync(() => { let nzSelectServiceStub: Partial; nzSelectServiceStub = { - check$ : new Subject(), - listOfSelectedValue$ : new Subject(), - open$ : new Subject(), - clearInput$ : new Subject(), - listOfSelectedValue : [ 1, 2, 3 ], + check$: new Subject(), + listOfSelectedValue$: new Subject(), + open$: new Subject(), + clearInput$: new Subject(), + listOfSelectedValue: [1, 2, 3], listOfCachedSelectedOption: createListOfOption(10), - isMultipleOrTags : true, - removeValueFormSelected : () => { - }, - tokenSeparate : () => { - }, - updateSearchValue : () => { - }, - updateListOfSelectedValue : () => { - }, - compareWith : (o1, o2) => o1 === o2 + isMultipleOrTags: true, + removeValueFormSelected: () => {}, + tokenSeparate: () => {}, + updateSearchValue: () => {}, + updateListOfSelectedValue: () => {}, + compareWith: (o1, o2) => o1 === o2 }; TestBed.configureTestingModule({ - providers : [ { provide: NzSelectService, useValue: nzSelectServiceStub } ], - imports : [ NzSelectModule, NoopAnimationsModule ], - declarations: [ NzTestSelectTopControlComponent ] + providers: [{ provide: NzSelectService, useValue: nzSelectServiceStub }], + imports: [NzSelectModule, NoopAnimationsModule], + declarations: [NzTestSelectTopControlComponent] }); TestBed.compileComponents(); })); @@ -169,12 +165,12 @@ describe('nz-select top control', () => { expect(removeSpy).toHaveBeenCalledTimes(1); }); }); - }); @Component({ template: ` -
    { [nzClearIcon]="nzClearIcon" [nzRemoveIcon]="nzRemoveIcon" [nzShowSearch]="nzShowSearch" - [nzTokenSeparators]="nzTokenSeparators"> -
    + [nzTokenSeparators]="nzTokenSeparators" + > nzMaxTagPlaceholder nzSuffixIcon nzClearIcon @@ -204,5 +200,5 @@ export class NzTestSelectTopControlComponent { nzShowArrow = true; nzLoading = false; nzShowSearch = false; - nzTokenSeparators = [ ',' ]; + nzTokenSeparators = [',']; } diff --git a/components/select/nz-select-unselectable.directive.ts b/components/select/nz-select-unselectable.directive.ts index 4cfe4c7d5b5..fbbc434355c 100644 --- a/components/select/nz-select-unselectable.directive.ts +++ b/components/select/nz-select-unselectable.directive.ts @@ -2,11 +2,9 @@ import { Directive } from '@angular/core'; @Directive({ selector: '[nz-select-unselectable]', - host : { + host: { '[attr.unselectable]': '"unselectable"', '[style.user-select]': '"none"' } }) -export class NzSelectUnselectableDirective { - -} +export class NzSelectUnselectableDirective {} diff --git a/components/select/nz-select-unselectable.spec.ts b/components/select/nz-select-unselectable.spec.ts index 3d2d593bd2f..616dd04af33 100644 --- a/components/select/nz-select-unselectable.spec.ts +++ b/components/select/nz-select-unselectable.spec.ts @@ -6,8 +6,8 @@ import { NzSelectUnselectableDirective } from './nz-select-unselectable.directiv describe('select unselectable', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [], - declarations: [ NzTestSelectUnselectableComponent, NzSelectUnselectableDirective ] + imports: [], + declarations: [NzTestSelectUnselectableComponent, NzSelectUnselectableDirective] }); TestBed.compileComponents(); })); @@ -30,7 +30,7 @@ describe('select unselectable', () => { @Component({ selector: 'nz-test-select-unselectable', template: ` -
    ` +
    + ` }) -export class NzTestSelectUnselectableComponent { -} +export class NzTestSelectUnselectableComponent {} diff --git a/components/select/nz-select.component.spec.ts b/components/select/nz-select.component.spec.ts index 430e0893d86..554fb321805 100644 --- a/components/select/nz-select.component.spec.ts +++ b/components/select/nz-select.component.spec.ts @@ -17,16 +17,22 @@ describe('nz-select component', () => { let overlayContainerElement: HTMLElement; beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzSelectModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestSelectDefaultComponent, NzTestSelectTagsComponent, NzTestSelectFormComponent, NzTestOptionChangeComponent, NzTestSelectFormDisabledTouchedComponent ] + imports: [NzSelectModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule], + declarations: [ + NzTestSelectDefaultComponent, + NzTestSelectTagsComponent, + NzTestSelectFormComponent, + NzTestOptionChangeComponent, + NzTestSelectFormDisabledTouchedComponent + ] }); TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -254,16 +260,16 @@ describe('nz-select component', () => { flush(); fixture.detectChanges(); expect(testComponent.selectedValue.length).toBe(1); - expect(testComponent.selectedValue[ 0 ]).toBe('jack'); + expect(testComponent.selectedValue[0]).toBe('jack'); })); it('should remove from top control work', fakeAsync(() => { fixture.detectChanges(); - selectComponent.nzSelectService.updateListOfSelectedValue([ 'jack' ], true); + selectComponent.nzSelectService.updateListOfSelectedValue(['jack'], true); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(testComponent.selectedValue.length).toBe(1); - expect(testComponent.selectedValue[ 0 ]).toBe('jack'); + expect(testComponent.selectedValue[0]).toBe('jack'); })); it('should clear work', fakeAsync(() => { fixture.detectChanges(); @@ -273,7 +279,6 @@ describe('nz-select component', () => { fixture.detectChanges(); expect(testComponent.selectedValue.length).toBe(0); })); - }); describe('form', () => { @@ -378,7 +383,6 @@ describe('nz-select component', () => { expect(testComponent.formGroup.controls.select.touched).toBe(false); })); }); - }); @Component({ @@ -403,7 +407,8 @@ describe('nz-select component', () => { [nzDropdownStyle]="dropdownStyle" [nzDropdownClassName]="'test-class'" (nzOnSearch)="onSearch($event)" - [nzPlaceHolder]="placeholder"> + [nzPlaceHolder]="placeholder" + > @@ -432,15 +437,12 @@ export class NzTestSelectDefaultComponent { } else { return false; } - } + }; } @Component({ template: ` - + Disabled @@ -448,16 +450,14 @@ export class NzTestSelectDefaultComponent { ` }) export class NzTestSelectTagsComponent { - selectedValue = [ 'lucy', 'jack' ]; + selectedValue = ['lucy', 'jack']; allowClear = false; } @Component({ template: `
    - + @@ -470,7 +470,7 @@ export class NzTestSelectFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - select: [ 'jack' ] + select: ['jack'] }); } @@ -486,8 +486,7 @@ export class NzTestSelectFormComponent { @Component({ template: ` - + diff --git a/components/select/nz-select.component.ts b/components/select/nz-select.component.ts index 89298f3572a..fa134c83924 100644 --- a/components/select/nz-select.component.ts +++ b/components/select/nz-select.component.ts @@ -37,40 +37,42 @@ import { NzSelectTopControlComponent } from './nz-select-top-control.component'; import { NzSelectService } from './nz-select.service'; @Component({ - selector : 'nz-select', + selector: 'nz-select', preserveWhitespaces: false, - providers : [ + providers: [ NzSelectService, { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzSelectComponent), - multi : true + multi: true } ], - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - animations : [ slideMotion ], - templateUrl : './nz-select.component.html', - host : { - '[class.ant-select-lg]' : 'nzSize==="large"', - '[class.ant-select-sm]' : 'nzSize==="small"', - '[class.ant-select-enabled]' : '!nzDisabled', - '[class.ant-select-no-arrow]' : '!nzShowArrow', - '[class.ant-select-disabled]' : 'nzDisabled', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + animations: [slideMotion], + templateUrl: './nz-select.component.html', + host: { + '[class.ant-select-lg]': 'nzSize==="large"', + '[class.ant-select-sm]': 'nzSize==="small"', + '[class.ant-select-enabled]': '!nzDisabled', + '[class.ant-select-no-arrow]': '!nzShowArrow', + '[class.ant-select-disabled]': 'nzDisabled', '[class.ant-select-allow-clear]': 'nzAllowClear', - '[class.ant-select-open]' : 'open', - '(click)' : 'toggleDropDown()' + '[class.ant-select-open]': 'open', + '(click)': 'toggleDropDown()' }, - styles : [ ` - .ant-select-dropdown { - top: 100%; - left: 0; - position: relative; - width: 100%; - margin-top: 4px; - margin-bottom: 4px; - } - ` ] + styles: [ + ` + .ant-select-dropdown { + top: 100%; + left: 0; + position: relative; + width: 100%; + margin-top: 4px; + margin-bottom: 4px; + } + ` + ] }) export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy, AfterContentInit { open = false; @@ -98,7 +100,7 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie @Input() nzSize: NzSizeLDSType = 'default'; @Input() nzDropdownClassName: string; @Input() nzDropdownMatchSelectWidth = true; - @Input() nzDropdownStyle: { [ key: string ]: string; }; + @Input() nzDropdownStyle: { [key: string]: string }; @Input() nzNotFoundContent: string; @Input() @InputBoolean() nzAllowClear = false; @Input() @InputBoolean() nzShowSearch = false; @@ -180,7 +182,11 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie updateAutoFocus(): void { if (this.nzSelectTopControlComponent.inputElement) { if (this.nzAutoFocus) { - this.renderer.setAttribute(this.nzSelectTopControlComponent.inputElement.nativeElement, 'autofocus', 'autofocus'); + this.renderer.setAttribute( + this.nzSelectTopControlComponent.inputElement.nativeElement, + 'autofocus', + 'autofocus' + ); } else { this.renderer.removeAttribute(this.nzSelectTopControlComponent.inputElement.nativeElement, 'autofocus'); } @@ -231,12 +237,14 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie }); } - constructor(private renderer: Renderer2, - public nzSelectService: NzSelectService, - private cdr: ChangeDetectorRef, - private focusMonitor: FocusMonitor, - elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + constructor( + private renderer: Renderer2, + public nzSelectService: NzSelectService, + private cdr: ChangeDetectorRef, + private focusMonitor: FocusMonitor, + elementRef: ElementRef, + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { renderer.addClass(elementRef.nativeElement, 'ant-select'); } @@ -249,7 +257,7 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie if (Array.isArray(value)) { listValue = value; } else { - listValue = [ value ]; + listValue = [value]; } } this.nzSelectService.updateListOfSelectedValue(listValue, false); @@ -270,24 +278,18 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie } ngOnInit(): void { - this.nzSelectService.searchValue$.pipe( - takeUntil(this.destroy$) - ).subscribe(data => { + this.nzSelectService.searchValue$.pipe(takeUntil(this.destroy$)).subscribe(data => { this.nzOnSearch.emit(data); this.updateCdkConnectedOverlayPositions(); }); - this.nzSelectService.modelChange$.pipe( - takeUntil(this.destroy$) - ).subscribe(modelValue => { + this.nzSelectService.modelChange$.pipe(takeUntil(this.destroy$)).subscribe(modelValue => { if (this.value !== modelValue) { this.value = modelValue; this.onChange(this.value); this.updateCdkConnectedOverlayPositions(); } }); - this.nzSelectService.open$.pipe( - takeUntil(this.destroy$) - ).subscribe((value) => { + this.nzSelectService.open$.pipe(takeUntil(this.destroy$)).subscribe(value => { if (this.open !== value) { this.nzOpenChange.emit(value); } @@ -300,9 +302,7 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie } this.open = value; }); - this.nzSelectService.check$.pipe( - takeUntil(this.destroy$) - ).subscribe(() => { + this.nzSelectService.check$.pipe(takeUntil(this.destroy$)).subscribe(() => { this.cdr.markForCheck(); }); } @@ -313,21 +313,25 @@ export class NzSelectComponent implements ControlValueAccessor, OnInit, AfterVie } ngAfterContentInit(): void { - this.listOfNzOptionGroupComponent.changes.pipe( - startWith(true), - flatMap(() => merge( - this.listOfNzOptionGroupComponent.changes, - this.listOfNzOptionComponent.changes, - ...this.listOfNzOptionGroupComponent.map(group => group.listOfNzOptionComponent ? group.listOfNzOptionComponent.changes : EMPTY) - ).pipe( - startWith(true) - )) - ).subscribe(() => { - this.nzSelectService.updateTemplateOption( - this.listOfNzOptionComponent.toArray(), - this.listOfNzOptionGroupComponent.toArray() - ); - }); + this.listOfNzOptionGroupComponent.changes + .pipe( + startWith(true), + flatMap(() => + merge( + this.listOfNzOptionGroupComponent.changes, + this.listOfNzOptionComponent.changes, + ...this.listOfNzOptionGroupComponent.map(group => + group.listOfNzOptionComponent ? group.listOfNzOptionComponent.changes : EMPTY + ) + ).pipe(startWith(true)) + ) + ) + .subscribe(() => { + this.nzSelectService.updateTemplateOption( + this.listOfNzOptionComponent.toArray(), + this.listOfNzOptionGroupComponent.toArray() + ); + }); } ngOnDestroy(): void { diff --git a/components/select/nz-select.module.ts b/components/select/nz-select.module.ts index 051146944a6..8fa81aeb794 100644 --- a/components/select/nz-select.module.ts +++ b/components/select/nz-select.module.ts @@ -18,7 +18,7 @@ import { NzSelectUnselectableDirective } from './nz-select-unselectable.directiv import { NzSelectComponent } from './nz-select.component'; @NgModule({ - imports : [ + imports: [ CommonModule, NzI18nModule, FormsModule, @@ -40,7 +40,7 @@ import { NzSelectComponent } from './nz-select.component'; NzSelectTopControlComponent, NzSelectUnselectableDirective ], - exports : [ + exports: [ NzOptionComponent, NzSelectComponent, NzOptionContainerComponent, @@ -48,5 +48,4 @@ import { NzSelectComponent } from './nz-select.component'; NzSelectTopControlComponent ] }) -export class NzSelectModule { -} +export class NzSelectModule {} diff --git a/components/select/nz-select.service.spec.ts b/components/select/nz-select.service.spec.ts index dd46f57b0f5..a18f44db7f8 100644 --- a/components/select/nz-select.service.spec.ts +++ b/components/select/nz-select.service.spec.ts @@ -8,7 +8,7 @@ describe('SelectService', () => { service = new NzSelectService(); }); describe('includesSeparators', () => { - const separators = [ ' ', ',' ]; + const separators = [' ', ',']; it('return true when given includes separators', () => { expect(service.includesSeparators(',foo,bar', separators)).toBe(true); }); @@ -23,20 +23,20 @@ describe('SelectService', () => { }); describe('splitBySeparators', () => { - const separators = [ ' ', ',' ]; + const separators = [' ', ',']; it('split given string by separators', () => { const str = 'foo bar,baz'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'foo', 'bar', 'baz' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['foo', 'bar', 'baz']); }); it('split string with leading separator ', () => { const str = ',foo'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'foo' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['foo']); }); it('split string with trailling separator', () => { const str = 'foo,'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'foo' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['foo']); }); it('split a separator', () => { @@ -51,21 +51,21 @@ describe('SelectService', () => { it('split two separators surrounded by valid input', () => { const str = 'a,,b'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'a', 'b' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['a', 'b']); }); it('split repeating separators with valid input throughout', () => { const str = ',,,a,b,,,c,d,,,e,'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'a', 'b', 'c', 'd', 'e' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['a', 'b', 'c', 'd', 'e']); }); it('split multiple repeating separators with valid input throughout', () => { const str = ',,,a b, c,d, ,e ,f'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'a', 'b', 'c', 'd', 'e', 'f' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['a', 'b', 'c', 'd', 'e', 'f']); }); it('split duplicated repeating separators with valid input throughout', () => { const str = ',,,a b, c,d, ,e ,f,a,b,c'; - expect(service.splitBySeparators(str, separators)).toEqual([ 'a', 'b', 'c', 'd', 'e', 'f' ]); + expect(service.splitBySeparators(str, separators)).toEqual(['a', 'b', 'c', 'd', 'e', 'f']); }); }); describe('tag', () => { @@ -73,13 +73,13 @@ describe('SelectService', () => { service.mode = 'tags'; }); it('should updateListOfTagOption work', () => { - service.listOfSelectedValue = [ `option_value_0`, `option_value_1`, `option_value_miss` ]; + service.listOfSelectedValue = [`option_value_0`, `option_value_1`, `option_value_miss`]; service.listOfTemplateOption = createListOfOption(3); service.updateListOfTagOption(); expect(service.listOfTagOption.length).toEqual(1); }); it('should updateAddTagOption work', () => { - service.listOfSelectedValue = [ `option_value_0`, `option_value_1` ]; + service.listOfSelectedValue = [`option_value_0`, `option_value_1`]; service.listOfTemplateOption = createListOfOption(3); service.searchValue = 'abc'; service.updateAddTagOption(); @@ -92,25 +92,25 @@ describe('SelectService', () => { service.mode = 'multiple'; const selectedValueSpy = spyOn(service, 'updateListOfSelectedValue'); service.listOfTagAndTemplateOption = createListOfOption(3); - service.tokenSeparate('option_label_0,b,c', [ ',' ]); - expect(selectedValueSpy).toHaveBeenCalledWith([ 'option_value_0' ], true); + service.tokenSeparate('option_label_0,b,c', [',']); + expect(selectedValueSpy).toHaveBeenCalledWith(['option_value_0'], true); }); it('should tags work', () => { service.mode = 'tags'; const selectedValueSpy = spyOn(service, 'updateListOfSelectedValue'); service.listOfTagAndTemplateOption = createListOfOption(3); - service.tokenSeparate('option_label_0,b,c', [ ',' ]); - expect(selectedValueSpy).toHaveBeenCalledWith([ 'option_value_0', 'b', 'c' ], true); + service.tokenSeparate('option_label_0,b,c', [',']); + expect(selectedValueSpy).toHaveBeenCalledWith(['option_value_0', 'b', 'c'], true); }); }); describe('remove', () => { it('should removeValueFormSelected work', () => { - service.listOfSelectedValue = [ 'a', 'b', 'c' ]; + service.listOfSelectedValue = ['a', 'b', 'c']; const selectedValueSpy = spyOn(service, 'updateListOfSelectedValue'); const option = new NzOptionComponent(); option.nzValue = 'a'; service.removeValueFormSelected(option); - expect(selectedValueSpy).toHaveBeenCalledWith([ 'b', 'c' ], true); + expect(selectedValueSpy).toHaveBeenCalledWith(['b', 'c'], true); }); }); }); diff --git a/components/select/nz-select.service.ts b/components/select/nz-select.service.ts index 8f17b2f1c8e..7365cffa275 100644 --- a/components/select/nz-select.service.ts +++ b/components/select/nz-select.service.ts @@ -20,16 +20,16 @@ export class NzSelectService { compareWith = (o1: any, o2: any) => o1 === o2; // selectedValueChanged should emit ngModelChange or not // tslint:disable-next-line:no-any - private listOfSelectedValueWithEmit$ = new BehaviorSubject<{ value: any[], emit: boolean }>({ + private listOfSelectedValueWithEmit$ = new BehaviorSubject<{ value: any[]; emit: boolean }>({ value: [], - emit : false + emit: false }); // ContentChildren Change private mapOfTemplateOption$ = new BehaviorSubject<{ - listOfNzOptionComponent: NzOptionComponent[], - listOfNzOptionGroupComponent: NzOptionGroupComponent[] + listOfNzOptionComponent: NzOptionComponent[]; + listOfNzOptionGroupComponent: NzOptionGroupComponent[]; }>({ - listOfNzOptionComponent : [], + listOfNzOptionComponent: [], listOfNzOptionGroupComponent: [] }); // searchValue Change @@ -57,7 +57,7 @@ export class NzSelectService { let modelValue: any[] | null = null; // tslint:disable-line:no-any if (this.isSingleMode) { if (selectedList.length) { - modelValue = selectedList[ 0 ]; + modelValue = selectedList[0]; } } else { modelValue = selectedList; @@ -69,10 +69,10 @@ export class NzSelectService { distinctUntilChanged(), skip(1), share(), - tap((value) => { + tap(value => { this.searchValue = value; if (value) { - this.updateActivatedOption(this.listOfFilteredOption[ 0 ]); + this.updateActivatedOption(this.listOfFilteredOption[0]); } this.updateListOfFilteredOption(); }) @@ -95,12 +95,13 @@ export class NzSelectService { // selected value or ViewChildren change valueOrOption$ = combineLatest(this.listOfSelectedValue$, this.mapOfTemplateOption$).pipe( tap(data => { - this.listOfSelectedValue = data[ 0 ]; - this.listOfNzOptionComponent = data[ 1 ].listOfNzOptionComponent; - this.listOfNzOptionGroupComponent = data[ 1 ].listOfNzOptionGroupComponent; + this.listOfSelectedValue = data[0]; + this.listOfNzOptionComponent = data[1].listOfNzOptionComponent; + this.listOfNzOptionGroupComponent = data[1].listOfNzOptionGroupComponent; this.listOfTemplateOption = this.listOfNzOptionComponent.concat( this.listOfNzOptionGroupComponent.reduce( - (pre, cur) => [ ...pre, ...cur.listOfNzOptionComponent.toArray() ], [] as NzOptionComponent[] + (pre, cur) => [...pre, ...cur.listOfNzOptionComponent.toArray()], + [] as NzOptionComponent[] ) ); this.updateListOfTagOption(); @@ -108,7 +109,8 @@ export class NzSelectService { this.resetActivatedOptionIfNeeded(); this.updateListOfCachedOption(); }), - share()); + share() + ); check$ = merge( this.checkRaw$, this.valueOrOption$, @@ -116,15 +118,13 @@ export class NzSelectService { this.activatedOption$, this.open$, this.modelChange$ - ).pipe( - share() - ); + ).pipe(share()); clickOption(option: NzOptionComponent): void { /** update listOfSelectedOption -> update listOfSelectedValue -> next listOfSelectedValue$ **/ if (!option.nzDisabled) { this.updateActivatedOption(option); - let listOfSelectedValue = [ ...this.listOfSelectedValue ]; + let listOfSelectedValue = [...this.listOfSelectedValue]; if (this.isMultipleOrTags) { const targetValue = listOfSelectedValue.find(o => this.compareWith(o, option.nzValue)); if (isNotNil(targetValue)) { @@ -134,8 +134,8 @@ export class NzSelectService { listOfSelectedValue.push(option.nzValue); this.updateListOfSelectedValue(listOfSelectedValue, true); } - } else if (!this.compareWith(listOfSelectedValue[ 0 ], option.nzValue)) { - listOfSelectedValue = [ option.nzValue ]; + } else if (!this.compareWith(listOfSelectedValue[0], option.nzValue)) { + listOfSelectedValue = [option.nzValue]; this.updateListOfSelectedValue(listOfSelectedValue, true); } if (this.isSingleMode) { @@ -148,14 +148,16 @@ export class NzSelectService { updateListOfCachedOption(): void { if (this.isSingleMode) { - const selectedOption = this.listOfTemplateOption.find(o => this.compareWith(o.nzValue, this.listOfSelectedValue[ 0 ])); + const selectedOption = this.listOfTemplateOption.find(o => + this.compareWith(o.nzValue, this.listOfSelectedValue[0]) + ); if (!isNil(selectedOption)) { - this.listOfCachedSelectedOption = [ selectedOption ]; + this.listOfCachedSelectedOption = [selectedOption]; } } else { const listOfCachedSelectedOption: NzOptionComponent[] = []; this.listOfSelectedValue.forEach(v => { - const listOfMixedOption = [ ...this.listOfTagAndTemplateOption, ...this.listOfCachedSelectedOption ]; + const listOfMixedOption = [...this.listOfTagAndTemplateOption, ...this.listOfCachedSelectedOption]; const option = listOfMixedOption.find(o => this.compareWith(o.nzValue, v)); if (option) { listOfCachedSelectedOption.push(option); @@ -167,16 +169,18 @@ export class NzSelectService { updateListOfTagOption(): void { if (this.isTagsMode) { - const listOfMissValue = this.listOfSelectedValue.filter(value => !this.listOfTemplateOption.find(o => this.compareWith(o.nzValue, value))); + const listOfMissValue = this.listOfSelectedValue.filter( + value => !this.listOfTemplateOption.find(o => this.compareWith(o.nzValue, value)) + ); this.listOfTagOption = listOfMissValue.map(value => { const nzOptionComponent = new NzOptionComponent(); nzOptionComponent.nzValue = value; nzOptionComponent.nzLabel = value; return nzOptionComponent; }); - this.listOfTagAndTemplateOption = [ ...this.listOfTemplateOption.concat(this.listOfTagOption) ]; + this.listOfTagAndTemplateOption = [...this.listOfTemplateOption.concat(this.listOfTagOption)]; } else { - this.listOfTagAndTemplateOption = [ ...this.listOfTemplateOption ]; + this.listOfTagAndTemplateOption = [...this.listOfTemplateOption]; } } @@ -201,7 +205,9 @@ export class NzSelectService { this.filterOption, this.serverSearch ); - this.listOfFilteredOption = this.addedTagOption ? [ this.addedTagOption, ...listOfFilteredOption ] : [ ...listOfFilteredOption ]; + this.listOfFilteredOption = this.addedTagOption + ? [this.addedTagOption, ...listOfFilteredOption] + : [...listOfFilteredOption]; this.isShowNotFound = !this.isTagsMode && !this.listOfFilteredOption.length; } @@ -221,11 +227,13 @@ export class NzSelectService { tokenSeparate(inputValue: string, tokenSeparators: string[]): void { // auto tokenSeparators - if (inputValue && + if ( + inputValue && inputValue.length && tokenSeparators.length && this.isMultipleOrTags && - this.includesSeparators(inputValue, tokenSeparators)) { + this.includesSeparators(inputValue, tokenSeparators) + ) { const listOfLabel = this.splitBySeparators(inputValue, tokenSeparators); this.updateSelectedValueByLabelList(listOfLabel); this.clearInput(); @@ -235,7 +243,7 @@ export class NzSelectService { includesSeparators(str: string | string[], separators: string[]): boolean { // tslint:disable-next-line:prefer-for-of for (let i = 0; i < separators.length; ++i) { - if (str.lastIndexOf(separators[ i ]) > 0) { + if (str.lastIndexOf(separators[i]) > 0) { return true; } } @@ -250,7 +258,9 @@ export class NzSelectService { resetActivatedOptionIfNeeded(): void { const resetActivatedOption = () => { - const activatedOption = this.listOfFilteredOption.find(item => this.compareWith(item.nzValue, this.listOfSelectedValue[ 0 ])); + const activatedOption = this.listOfFilteredOption.find(item => + this.compareWith(item.nzValue, this.listOfSelectedValue[0]) + ); this.updateActivatedOption(activatedOption || null); }; if (this.activatedOption) { @@ -265,7 +275,10 @@ export class NzSelectService { } } - updateTemplateOption(listOfNzOptionComponent: NzOptionComponent[], listOfNzOptionGroupComponent: NzOptionGroupComponent[]): void { + updateTemplateOption( + listOfNzOptionComponent: NzOptionComponent[], + listOfNzOptionGroupComponent: NzOptionGroupComponent[] + ): void { this.mapOfTemplateOption$.next({ listOfNzOptionComponent, listOfNzOptionGroupComponent }); } @@ -274,19 +287,21 @@ export class NzSelectService { } updateSelectedValueByLabelList(listOfLabel: string[]): void { - const listOfSelectedValue = [ ...this.listOfSelectedValue ]; + const listOfSelectedValue = [...this.listOfSelectedValue]; const listOfMatchOptionValue = this.listOfTagAndTemplateOption - .filter(item => listOfLabel.indexOf(item.nzLabel) !== -1) - .map(item => item.nzValue) - .filter(item => !isNotNil(this.listOfSelectedValue.find(v => this.compareWith(v, item)))); + .filter(item => listOfLabel.indexOf(item.nzLabel) !== -1) + .map(item => item.nzValue) + .filter(item => !isNotNil(this.listOfSelectedValue.find(v => this.compareWith(v, item)))); if (this.isMultipleMode) { - this.updateListOfSelectedValue([ ...listOfSelectedValue, ...listOfMatchOptionValue ], true); + this.updateListOfSelectedValue([...listOfSelectedValue, ...listOfMatchOptionValue], true); } else { - const listOfUnMatchOptionValue = listOfLabel - .filter(label => this.listOfTagAndTemplateOption - .map(item => item.nzLabel).indexOf(label) === -1 + const listOfUnMatchOptionValue = listOfLabel.filter( + label => this.listOfTagAndTemplateOption.map(item => item.nzLabel).indexOf(label) === -1 + ); + this.updateListOfSelectedValue( + [...listOfSelectedValue, ...listOfMatchOptionValue, ...listOfUnMatchOptionValue], + true ); - this.updateListOfSelectedValue([ ...listOfSelectedValue, ...listOfMatchOptionValue, ...listOfUnMatchOptionValue ], true); } } @@ -298,13 +313,13 @@ export class NzSelectService { switch (keyCode) { case UP_ARROW: e.preventDefault(); - const preIndex = activatedIndex > 0 ? (activatedIndex - 1) : (listOfFilteredOptionWithoutDisabled.length - 1); - this.updateActivatedOption(listOfFilteredOptionWithoutDisabled[ preIndex ]); + const preIndex = activatedIndex > 0 ? activatedIndex - 1 : listOfFilteredOptionWithoutDisabled.length - 1; + this.updateActivatedOption(listOfFilteredOptionWithoutDisabled[preIndex]); break; case DOWN_ARROW: e.preventDefault(); - const nextIndex = activatedIndex < listOfFilteredOptionWithoutDisabled.length - 1 ? (activatedIndex + 1) : 0; - this.updateActivatedOption(listOfFilteredOptionWithoutDisabled[ nextIndex ]); + const nextIndex = activatedIndex < listOfFilteredOptionWithoutDisabled.length - 1 ? activatedIndex + 1 : 0; + this.updateActivatedOption(listOfFilteredOptionWithoutDisabled[nextIndex]); if (!this.disabled && !this.open) { this.setOpenState(true); } @@ -322,7 +337,7 @@ export class NzSelectService { case BACKSPACE: if (this.isMultipleOrTags && !eventTarget.value && this.listOfCachedSelectedOption.length) { e.preventDefault(); - this.removeValueFormSelected(this.listOfCachedSelectedOption[ this.listOfCachedSelectedOption.length - 1 ]); + this.removeValueFormSelected(this.listOfCachedSelectedOption[this.listOfCachedSelectedOption.length - 1]); } break; case SPACE: diff --git a/components/skeleton/demo/active.ts b/components/skeleton/demo/active.ts index cdf52a5d172..a71ab8acf15 100644 --- a/components/skeleton/demo/active.ts +++ b/components/skeleton/demo/active.ts @@ -6,4 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoSkeletonActiveComponent { } +export class NzDemoSkeletonActiveComponent {} diff --git a/components/skeleton/demo/basic.ts b/components/skeleton/demo/basic.ts index a8f24b1da7d..43a84b23e56 100644 --- a/components/skeleton/demo/basic.ts +++ b/components/skeleton/demo/basic.ts @@ -6,4 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoSkeletonBasicComponent { } +export class NzDemoSkeletonBasicComponent {} diff --git a/components/skeleton/demo/children.ts b/components/skeleton/demo/children.ts index d8fbca3f938..b715611a960 100644 --- a/components/skeleton/demo/children.ts +++ b/components/skeleton/demo/children.ts @@ -6,14 +6,17 @@ import { Component } from '@angular/core';

    Ant Design, a design language

    -

    We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.

    +

    + We supply a series of design principles, practical patterns and high quality design resources (Sketch and + Axure), to help people create their product prototypes beautifully and efficiently. +

    `, - styles : [ + styles: [ ` .article h4 { margin-bottom: 16px; diff --git a/components/skeleton/demo/complex.ts b/components/skeleton/demo/complex.ts index e84122136f3..81312cf1b3e 100644 --- a/components/skeleton/demo/complex.ts +++ b/components/skeleton/demo/complex.ts @@ -6,4 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoSkeletonComplexComponent { } +export class NzDemoSkeletonComplexComponent {} diff --git a/components/skeleton/demo/list.ts b/components/skeleton/demo/list.ts index 1b148ad2e2b..cfab1cfc3d5 100644 --- a/components/skeleton/demo/list.ts +++ b/components/skeleton/demo/list.ts @@ -6,19 +6,22 @@ import { Component } from '@angular/core'; - + 156 156 2 - - {{item.title}} + + {{ item.title }} - logo + logo @@ -34,7 +37,8 @@ export class NzDemoSkeletonListComponent { title: `ant design part ${index}`, avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.', - content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' + content: + 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.' }; }); } diff --git a/components/skeleton/nz-skeleton.component.ts b/components/skeleton/nz-skeleton.component.ts index 3ecb83c3b5d..49d4d3fe4f7 100644 --- a/components/skeleton/nz-skeleton.component.ts +++ b/components/skeleton/nz-skeleton.component.ts @@ -1,7 +1,8 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, + Component, + ElementRef, Input, OnChanges, OnInit, @@ -15,12 +16,12 @@ import { AvatarShape, AvatarSize, NzSkeletonAvatar, NzSkeletonParagraph, NzSkele @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-skeleton', - templateUrl : './nz-skeleton.component.html', - host : { + encapsulation: ViewEncapsulation.None, + selector: 'nz-skeleton', + templateUrl: './nz-skeleton.component.html', + host: { '[class.ant-skeleton-with-avatar]': '!!nzAvatar', - '[class.ant-skeleton-active]' : 'nzActive' + '[class.ant-skeleton-active]': 'nzActive' } }) export class NzSkeletonComponent implements OnInit, OnChanges { @@ -57,7 +58,7 @@ export class NzSkeletonComponent implements OnInit, OnChanges { } private getAvatarProps(): NzSkeletonAvatar { - const shape: AvatarShape = (!!this.nzTitle && !this.nzParagraph) ? 'square' : 'circle'; + const shape: AvatarShape = !!this.nzTitle && !this.nzParagraph ? 'square' : 'circle'; const size: AvatarSize = 'large'; return { shape, size, ...this.getProps(this.nzAvatar) }; } @@ -90,7 +91,7 @@ export class NzSkeletonComponent implements OnInit, OnChanges { widthList = width; } else if (width && !Array.isArray(width)) { widthList = []; - widthList[ rows! - 1 ] = width; + widthList[rows! - 1] = width; } return widthList; } @@ -99,7 +100,7 @@ export class NzSkeletonComponent implements OnInit, OnChanges { this.title = this.getTitleProps(); this.avatar = this.getAvatarProps(); this.paragraph = this.getParagraphProps(); - this.rowsList = [ ...Array(this.paragraph.rows) ]; + this.rowsList = [...Array(this.paragraph.rows)]; this.widthList = this.getWidthList(); this.cdr.markForCheck(); } diff --git a/components/skeleton/nz-skeleton.module.ts b/components/skeleton/nz-skeleton.module.ts index c03e0dd1579..3eb520dd223 100644 --- a/components/skeleton/nz-skeleton.module.ts +++ b/components/skeleton/nz-skeleton.module.ts @@ -3,8 +3,8 @@ import { NgModule } from '@angular/core'; import { NzSkeletonComponent } from './nz-skeleton.component'; @NgModule({ - declarations: [ NzSkeletonComponent ], - imports : [ CommonModule ], - exports : [ NzSkeletonComponent ] + declarations: [NzSkeletonComponent], + imports: [CommonModule], + exports: [NzSkeletonComponent] }) export class NzSkeletonModule {} diff --git a/components/skeleton/nz-skeleton.spec.ts b/components/skeleton/nz-skeleton.spec.ts index 6d0a3058ab9..b2be1553cbc 100644 --- a/components/skeleton/nz-skeleton.spec.ts +++ b/components/skeleton/nz-skeleton.spec.ts @@ -134,12 +134,7 @@ describe('skeleton', () => { @Component({ selector: 'nz-test-skeleton', template: ` - + ` }) @@ -147,5 +142,5 @@ export class NzTestSkeletonComponent { nzActive: boolean; nzAvatar: NzSkeletonAvatar | boolean; nzTitle: NzSkeletonTitle | boolean; - nzParagraph: NzSkeletonParagraph | boolean ; + nzParagraph: NzSkeletonParagraph | boolean; } diff --git a/components/slider/demo/basic.ts b/components/slider/demo/basic.ts index edd1e693e57..8ec41b7fa21 100644 --- a/components/slider/demo/basic.ts +++ b/components/slider/demo/basic.ts @@ -12,5 +12,5 @@ import { Component } from '@angular/core'; export class NzDemoSliderBasicComponent { disabled = false; value1 = 30; - value2 = [ 20, 50 ]; + value2 = [20, 50]; } diff --git a/components/slider/demo/event.ts b/components/slider/demo/event.ts index df0c125ea5c..00abef5c3cc 100644 --- a/components/slider/demo/event.ts +++ b/components/slider/demo/event.ts @@ -3,13 +3,23 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-slider-event', template: ` - - + + ` }) export class NzDemoSliderEventComponent { singleValue = 30; - rangeValue = [ 20, 50 ]; + rangeValue = [20, 50]; onChange(value: number): void { console.log(`onChange: ${value}`); @@ -18,5 +28,4 @@ export class NzDemoSliderEventComponent { onAfterChange(value: number): void { console.log(`onAfterChange: ${value}`); } - } diff --git a/components/slider/demo/icon-slider.ts b/components/slider/demo/icon-slider.ts index 31de34d5a3e..d6330620d23 100644 --- a/components/slider/demo/icon-slider.ts +++ b/components/slider/demo/icon-slider.ts @@ -9,7 +9,7 @@ import { Component, OnInit } from '@angular/core'; `, - styles : [ + styles: [ ` .icon-wrapper { position: relative; @@ -23,7 +23,7 @@ import { Component, OnInit } from '@angular/core'; height: 16px; line-height: 1; font-size: 16px; - color: rgba(0, 0, 0, .25); + color: rgba(0, 0, 0, 0.25); } [nz-icon]:first-child { @@ -34,14 +34,13 @@ import { Component, OnInit } from '@angular/core'; right: 0; } - .icon-highlight{ + .icon-highlight { color: rgba(0, 0, 0, 0.45); } ` ] }) export class NzDemoSliderIconSliderComponent implements OnInit { - min = 0; max = 20; mid = parseFloat(((this.max - this.min) / 2).toFixed(5)); @@ -67,5 +66,4 @@ export class NzDemoSliderIconSliderComponent implements OnInit { this.preHighLight = !lower; this.nextHighLight = lower; } - } diff --git a/components/slider/demo/input-number.ts b/components/slider/demo/input-number.ts index 3e31de31d7a..20c9784783d 100644 --- a/components/slider/demo/input-number.ts +++ b/components/slider/demo/input-number.ts @@ -3,13 +3,17 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-slider-input-number', template: ` -
    - +
    @@ -18,15 +22,18 @@ import { Component } from '@angular/core'; - + - ` }) export class NzDemoSliderInputNumberComponent { - value1 = 1; value2 = 0; - } diff --git a/components/slider/demo/mark.ts b/components/slider/demo/mark.ts index 5ed9e3d9ca3..97dfc8bf097 100644 --- a/components/slider/demo/mark.ts +++ b/components/slider/demo/mark.ts @@ -17,35 +17,35 @@ import { Component } from '@angular/core'; Change nzMarks dynamically: `, - styles : [ ` - h4 { - margin: 0 0 16px; - } + styles: [ + ` + h4 { + margin: 0 0 16px; + } - .ant-slider-with-marks { - margin-bottom: 44px; - } - ` ] + .ant-slider-with-marks { + margin-bottom: 44px; + } + ` + ] }) export class NzDemoSliderMarkComponent { - marks: any = { - 0 : '0°C', - 26 : '26°C', - 37 : '37°C', + 0: '0°C', + 26: '26°C', + 37: '37°C', 100: { style: { - color: '#f50', + color: '#f50' }, - label: '100°C', + label: '100°C' } }; changeMarks() { this.marks = { 20: '20%', - 99: '99%', + 99: '99%' }; } - } diff --git a/components/slider/demo/tooltip.ts b/components/slider/demo/tooltip.ts index 926c1f937d6..f9b13ecd59a 100644 --- a/components/slider/demo/tooltip.ts +++ b/components/slider/demo/tooltip.ts @@ -7,5 +7,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoSliderTooltipComponent { -} +export class NzDemoSliderTooltipComponent {} diff --git a/components/slider/demo/vertical.ts b/components/slider/demo/vertical.ts index 790b2853b64..2df3f50a85c 100644 --- a/components/slider/demo/vertical.ts +++ b/components/slider/demo/vertical.ts @@ -17,23 +17,21 @@ import { Component } from '@angular/core'; ` }) export class NzDemoSliderVerticalComponent { - style = { - float : 'left', - height : '300px', + float: 'left', + height: '300px', marginLeft: '70px' }; marks = { - 0 : '0°C', - 26 : '26°C', - 37 : '37°C', + 0: '0°C', + 26: '26°C', + 37: '37°C', 100: { style: { - color: '#f50', + color: '#f50' }, - label: '100°C', + label: '100°C' } }; - } diff --git a/components/slider/nz-slider-definitions.ts b/components/slider/nz-slider-definitions.ts index f936cbf5381..13843487c0c 100644 --- a/components/slider/nz-slider-definitions.ts +++ b/components/slider/nz-slider-definitions.ts @@ -6,7 +6,7 @@ export interface MarkObj { } export class Marks { - [ key: number ]: Mark; + [key: number]: Mark; } /** diff --git a/components/slider/nz-slider-error.ts b/components/slider/nz-slider-error.ts index 210642e0bf9..f9170c5f33f 100644 --- a/components/slider/nz-slider-error.ts +++ b/components/slider/nz-slider-error.ts @@ -1,3 +1,5 @@ export function getValueTypeNotMatchError(): Error { - return new Error(`The "nzRange" can't match the "ngModel"'s type, please check these properties: "nzRange", "ngModel", "nzDefaultValue".`); + return new Error( + `The "nzRange" can't match the "ngModel"'s type, please check these properties: "nzRange", "ngModel", "nzDefaultValue".` + ); } diff --git a/components/slider/nz-slider-handle.component.ts b/components/slider/nz-slider-handle.component.ts index 53e3faf2c19..e062f82769b 100644 --- a/components/slider/nz-slider-handle.component.ts +++ b/components/slider/nz-slider-handle.component.ts @@ -19,12 +19,12 @@ import { SliderShowTooltip } from './nz-slider-definitions'; import { NzSliderComponent } from './nz-slider.component'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-slider-handle', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-slider-handle', preserveWhitespaces: false, - templateUrl : './nz-slider-handle.component.html', - host : { + templateUrl: './nz-slider-handle.component.html', + host: { '(mouseenter)': 'enterHandle()', '(mouseleave)': 'leaveHandle()' } @@ -44,11 +44,7 @@ export class NzSliderHandleComponent implements OnChanges, OnDestroy { private hovers_ = new Subscription(); - constructor( - private sliderComponent: NzSliderComponent, - private cdr: ChangeDetectorRef - ) { - } + constructor(private sliderComponent: NzSliderComponent, private cdr: ChangeDetectorRef) {} ngOnChanges(changes: SimpleChanges): void { const { nzOffset, nzValue, nzActive, nzTooltipVisible } = changes; @@ -82,14 +78,14 @@ export class NzSliderHandleComponent implements OnChanges, OnDestroy { this.updateTooltipPosition(); this.cdr.detectChanges(); } - } + }; leaveHandle = () => { if (!this.sliderComponent.isDragging) { this.toggleTooltip(false); this.cdr.detectChanges(); } - } + }; private toggleTooltip(show: boolean, force: boolean = false): void { if (!force && (this.nzTooltipVisible !== 'default' || !this.tooltip)) { @@ -114,6 +110,6 @@ export class NzSliderHandleComponent implements OnChanges, OnDestroy { } private updateStyle(): void { - this.style[ this.nzVertical ? 'bottom' : 'left' ] = `${this.nzOffset}%`; + this.style[this.nzVertical ? 'bottom' : 'left'] = `${this.nzOffset}%`; } } diff --git a/components/slider/nz-slider-marks.component.ts b/components/slider/nz-slider-marks.component.ts index 7a487a1f391..a09a8aa031c 100644 --- a/components/slider/nz-slider-marks.component.ts +++ b/components/slider/nz-slider-marks.component.ts @@ -5,11 +5,11 @@ import { InputBoolean } from '../core/util/convert'; import { isConfigAObject, DisplayedMark, ExtendedMark, Mark } from './nz-slider-definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - selector : 'nz-slider-marks', - templateUrl : './nz-slider-marks.component.html' + selector: 'nz-slider-marks', + templateUrl: './nz-slider-marks.component.html' }) export class NzSliderMarksComponent implements OnChanges { @Input() nzLowerBound: number | null = null; @@ -54,22 +54,22 @@ export class NzSliderMarksComponent implements OnChanges { }); } - private buildStyles(value: number, range: number, config: Mark): { [ key: string ]: string } { + private buildStyles(value: number, range: number, config: Mark): { [key: string]: string } { let style; if (this.nzVertical) { style = { marginBottom: '-50%', - bottom : `${(value - this.nzMin) / range * 100}%` + bottom: `${((value - this.nzMin) / range) * 100}%` }; } else { const marksCount = this.nzMarksArray.length; const unit = 100 / (marksCount - 1); const markWidth = unit * 0.9; style = { - width : `${markWidth}%`, + width: `${markWidth}%`, marginLeft: `${-markWidth / 2}%`, - left : `${(value - this.nzMin) / range * 100}%` + left: `${((value - this.nzMin) / range) * 100}%` }; } diff --git a/components/slider/nz-slider-step.component.ts b/components/slider/nz-slider-step.component.ts index 5dbe54787d6..001d7703d41 100644 --- a/components/slider/nz-slider-step.component.ts +++ b/components/slider/nz-slider-step.component.ts @@ -5,11 +5,11 @@ import { InputBoolean } from '../core/util/convert'; import { DisplayedStep, ExtendedMark } from './nz-slider-definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-slider-step', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-slider-step', preserveWhitespaces: false, - templateUrl : './nz-slider-step.component.html' + templateUrl: './nz-slider-step.component.html' }) export class NzSliderStepComponent implements OnChanges { @Input() nzLowerBound: number | null = null; @@ -44,8 +44,8 @@ export class NzSliderStepComponent implements OnChanges { offset, config, active: false, - style : { - [ orient ]: `${offset}%` + style: { + [orient]: `${offset}%` } }; }); diff --git a/components/slider/nz-slider-track.component.ts b/components/slider/nz-slider-track.component.ts index 16d637aff1a..232796bad99 100644 --- a/components/slider/nz-slider-track.component.ts +++ b/components/slider/nz-slider-track.component.ts @@ -11,11 +11,11 @@ export interface NzSliderTrackStyle { } @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-slider-track', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-slider-track', preserveWhitespaces: false, - templateUrl : './nz-slider-track.component.html' + templateUrl: './nz-slider-track.component.html' }) export class NzSliderTrackComponent implements OnChanges { @Input() @InputNumber() nzOffset: number; diff --git a/components/slider/nz-slider.component.ts b/components/slider/nz-slider.component.ts index d67afc79c92..69e567b8382 100644 --- a/components/slider/nz-slider.component.ts +++ b/components/slider/nz-slider.component.ts @@ -35,16 +35,18 @@ import { import { getValueTypeNotMatchError } from './nz-slider-error'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-slider', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-slider', preserveWhitespaces: false, - providers : [ { - provide : NG_VALUE_ACCESSOR, - useExisting: forwardRef(() => NzSliderComponent), - multi : true - } ], - templateUrl : './nz-slider.component.html' + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => NzSliderComponent), + multi: true + } + ], + templateUrl: './nz-slider.component.html' }) export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChanges, OnDestroy { @ViewChild('slider') slider: ElementRef; @@ -69,10 +71,10 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange cacheSliderStart: number | null = null; cacheSliderLength: number | null = null; activeValueIndex: number | undefined = undefined; // Current activated handle's index ONLY for range=true - track: { offset: null | number, length: null | number } = { offset: null, length: null }; // Track's offset and length + track: { offset: null | number; length: null | number } = { offset: null, length: null }; // Track's offset and length handles: SliderHandler[]; // Handles' offset marksArray: ExtendedMark[] | null; // "steps" in array type with more data & FILTER out the invalid mark - bounds: { lower: SliderValue | null, upper: SliderValue | null } = { lower: null, upper: null }; // now for nz-slider-step + bounds: { lower: SliderValue | null; upper: SliderValue | null } = { lower: null, upper: null }; // now for nz-slider-step isDragging = false; // Current dragging state private dragStart$: Observable; @@ -116,11 +118,9 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange this.setValue(val, true); } - onValueChange(_value: SliderValue): void { - } + onValueChange(_value: SliderValue): void {} - onTouched(): void { - } + onTouched(): void {} registerOnChange(fn: (value: SliderValue) => void): void { this.onValueChange = fn; @@ -191,7 +191,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange private setActiveValue(pointerValue: number): void { if (isValueARange(this.value!)) { const newValue = shallowCopyArray(this.value as number[]); - newValue[ this.activeValueIndex! ] = pointerValue; + newValue[this.activeValueIndex!] = pointerValue; this.setValue(newValue); } else { this.setValue(pointerValue); @@ -206,18 +206,18 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange const offset = this.getValueToOffset(value); const valueSorted = this.getValue(true); const offsetSorted = this.getValueToOffset(valueSorted); - const boundParts = isValueARange(valueSorted) ? valueSorted : [ 0, valueSorted ]; + const boundParts = isValueARange(valueSorted) ? valueSorted : [0, valueSorted]; const trackParts = isValueARange(offsetSorted) - ? [ offsetSorted[ 0 ], offsetSorted[ 1 ] - offsetSorted[ 0 ] ] - : [ 0, offsetSorted ]; + ? [offsetSorted[0], offsetSorted[1] - offsetSorted[0]] + : [0, offsetSorted]; this.handles.forEach((handle, index) => { - handle.offset = isValueARange(offset) ? offset[ index ] : offset; - handle.value = isValueARange(value) ? value[ index ] : value || 0; + handle.offset = isValueARange(offset) ? offset[index] : offset; + handle.value = isValueARange(value) ? value[index] : value || 0; }); - [ this.bounds.lower, this.bounds.upper ] = boundParts; - [ this.track.offset, this.track.length ] = trackParts; + [this.bounds.lower, this.bounds.upper] = boundParts; + [this.track.offset, this.track.length] = trackParts; this.cdr.markForCheck(); } @@ -250,21 +250,21 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange const sliderDOM = this.sliderDOM; const orientField = this.nzVertical ? 'pageY' : 'pageX'; const mouse: MouseTouchObserverConfig = { - start : 'mousedown', - move : 'mousemove', - end : 'mouseup', - pluckKey: [ orientField ] + start: 'mousedown', + move: 'mousemove', + end: 'mouseup', + pluckKey: [orientField] }; const touch: MouseTouchObserverConfig = { - start : 'touchstart', - move : 'touchmove', - end : 'touchend', - pluckKey: [ 'touches', '0', orientField ], - filter : (e: MouseEvent | TouchEvent) => e instanceof TouchEvent + start: 'touchstart', + move: 'touchmove', + end: 'touchend', + pluckKey: ['touches', '0', orientField], + filter: (e: MouseEvent | TouchEvent) => e instanceof TouchEvent }; - [ mouse, touch ].forEach(source => { - const { start, move, end, pluckKey, filter: filterFunc = (() => true) } = source; + [mouse, touch].forEach(source => { + const { start, move, end, pluckKey, filter: filterFunc = () => true } = source; source.startPlucked$ = fromEvent(sliderDOM, start).pipe( filter(filterFunc), @@ -289,7 +289,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange this.dragEnd$ = merge(mouse.end$!, touch.end$!); } - private subscribeDrag(periods: string[] = [ 'start', 'move', 'end' ]): void { + private subscribeDrag(periods: string[] = ['start', 'move', 'end']): void { if (periods.indexOf('start') !== -1 && this.dragStart$ && !this.dragStart_) { this.dragStart_ = this.dragStart$.subscribe(this.onDragStart.bind(this)); } @@ -303,7 +303,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange } } - private unsubscribeDrag(periods: string[] = [ 'start', 'move', 'end' ]): void { + private unsubscribeDrag(periods: string[] = ['start', 'move', 'end']): void { if (periods.indexOf('start') !== -1 && this.dragStart_) { this.dragStart_.unsubscribe(); this.dragStart_ = null; @@ -321,7 +321,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange } private toggleDragMoving(movable: boolean): void { - const periods = [ 'move', 'end' ]; + const periods = ['move', 'end']; if (movable) { this.isDragging = true; this.subscribeDrag(periods); @@ -335,7 +335,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange if (disabled) { this.unsubscribeDrag(); } else { - this.subscribeDrag([ 'start' ]); + this.subscribeDrag(['start']); } } @@ -344,13 +344,13 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange const sliderLength = this.getSliderLength(); const ratio = ensureNumberInRange((position - sliderStart) / sliderLength, 0, 1); const val = (this.nzMax - this.nzMin) * (this.nzVertical ? 1 - ratio : ratio) + this.nzMin; - const points = (this.nzMarks === null ? [] : Object.keys(this.nzMarks).map(parseFloat)); + const points = this.nzMarks === null ? [] : Object.keys(this.nzMarks).map(parseFloat); if (this.nzStep !== null && !this.nzDots) { const closestOne = Math.round(val / this.nzStep) * this.nzStep; points.push(closestOne); } const gaps = points.map(point => Math.abs(val - point)); - const closest = points[ gaps.indexOf(Math.min(...gaps)) ]; + const closest = points[gaps.indexOf(Math.min(...gaps))]; return this.nzStep === null ? closest : parseFloat(closest.toFixed(getPrecision(this.nzStep))); } @@ -385,9 +385,7 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange private formatValue(value: SliderValue | null): SliderValue { let res = value; if (!this.assertValueValid(value!)) { - res = this.nzDefaultValue === null - ? (this.nzRange ? [ this.nzMin, this.nzMax ] : this.nzMin) - : this.nzDefaultValue; + res = this.nzDefaultValue === null ? (this.nzRange ? [this.nzMin, this.nzMax] : this.nzMin) : this.nzDefaultValue; } else { res = isValueARange(value!) ? (value as number[]).map(val => ensureNumberInRange(val, this.nzMin, this.nzMax)) @@ -437,17 +435,19 @@ export class NzSliderComponent implements ControlValueAccessor, OnInit, OnChange } private hideAllHandleTooltip(): void { - this.handles.forEach(handle => handle.active = false); + this.handles.forEach(handle => (handle.active = false)); } private generateHandles(amount: number): SliderHandler[] { - return Array(amount).fill(0).map(() => ({ offset: null, value: null, active: false })); + return Array(amount) + .fill(0) + .map(() => ({ offset: null, value: null, active: false })); } private generateMarkItems(marks: Marks): ExtendedMark[] | null { const marksArray: ExtendedMark[] = []; for (const key in marks) { - const mark = marks[ key ]; + const mark = marks[key]; const val = typeof key === 'number' ? key : parseFloat(key); if (val >= this.nzMin && val <= this.nzMax) { marksArray.push({ value: val, offset: this.valueToOffset(val), config: mark }); diff --git a/components/slider/nz-slider.module.ts b/components/slider/nz-slider.module.ts index d95f06ab833..a7e167b3810 100644 --- a/components/slider/nz-slider.module.ts +++ b/components/slider/nz-slider.module.ts @@ -24,6 +24,6 @@ import { NzSliderComponent } from './nz-slider.component'; NzSliderStepComponent, NzSliderMarksComponent ], - imports: [ CommonModule, NzToolTipModule ] + imports: [CommonModule, NzToolTipModule] }) -export class NzSliderModule { } +export class NzSliderModule {} diff --git a/components/slider/nz-slider.spec.ts b/components/slider/nz-slider.spec.ts index a9ae2229a5f..80f1e8ecc55 100644 --- a/components/slider/nz-slider.spec.ts +++ b/components/slider/nz-slider.spec.ts @@ -13,7 +13,7 @@ import { NzSliderModule } from './nz-slider.module'; describe('NzSlider', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzSliderModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule ], + imports: [NzSliderModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule], declarations: [ StandardSliderComponent, DisableSliderComponent, @@ -124,7 +124,6 @@ describe('NzSlider', () => { expect(onChangeSpy).toHaveBeenCalledTimes(1); }); - }); describe('show tooltip', () => { @@ -135,7 +134,7 @@ describe('NzSlider', () => { let testComponent: SliderShowTooltipComponent; let overlayContainerElement: HTMLElement; - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainerElement = oc.getContainerElement(); })); @@ -202,7 +201,7 @@ describe('NzSlider', () => { sliderNativeElement = sliderInstance.sliderDOM; }); - it('should/shouldn\'t be disabled', () => { + it("should/shouldn't be disabled", () => { expect(sliderInstance.nzDisabled).toBeTruthy(); testComponent.disable = false; @@ -270,7 +269,7 @@ describe('NzSlider', () => { // Computed by multiplying the difference between the min and the max by the percentage from // the click and adding that to the minimum. - const value = Math.round(((6 - 4) * 0.09) + 4); + const value = Math.round((6 - 4) * 0.09 + 4); expect(sliderInstance.value).toBe(value); }); @@ -280,7 +279,7 @@ describe('NzSlider', () => { // Computed by multiplying the difference between the min and the max by the percentage from // the click and adding that to the minimum. - const value = Math.round(((6 - 4) * 0.62) + 4); + const value = Math.round((6 - 4) * 0.62 + 4); expect(sliderInstance.value).toBe(value); }); @@ -532,7 +531,7 @@ describe('NzSlider', () => { trackFillElement = sliderNativeElement.querySelector('.ant-slider-track') as HTMLElement; }); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainerElement = oc.getContainerElement(); })); @@ -547,10 +546,10 @@ describe('NzSlider', () => { dispatchClickEventSequence(sliderNativeElement, 0.6); fixture.detectChanges(); - expect(sliderInstance.value).toEqual([ 10, 60 ]); + expect(sliderInstance.value).toEqual([10, 60]); }); - it('should/shouldn\'t be included', () => { + it("should/shouldn't be included", () => { dispatchClickEventSequence(sliderNativeElement, 0.33); fixture.detectChanges(); expect(trackFillElement.style.left).toBe('0%'); @@ -573,7 +572,7 @@ describe('NzSlider', () => { }); it('should stop at new steps when step=null or dots=true', () => { - testComponent.marks = { 15: { style: { 'color': 'red' }, label: '15' }, 33: '33' } as any; // tslint:disable-line:no-any + testComponent.marks = { 15: { style: { color: 'red' }, label: '15' }, 33: '33' } as any; // tslint:disable-line:no-any testComponent.step = null; fixture.detectChanges(); @@ -724,16 +723,17 @@ const styles = ` @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) -class StandardSliderComponent { -} +class StandardSliderComponent {} @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) class DisableSliderComponent { disable = true; @@ -741,8 +741,9 @@ class DisableSliderComponent { @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) class SliderWithMinAndMaxComponent { min = 4; @@ -751,16 +752,17 @@ class SliderWithMinAndMaxComponent { @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) -class SliderWithValueComponent { -} +class SliderWithValueComponent {} @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) class SliderWithStepComponent { step = 25; @@ -768,33 +770,40 @@ class SliderWithStepComponent { @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) -class SliderWithValueSmallerThanMinComponent { -} +class SliderWithValueSmallerThanMinComponent {} @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) -class SliderWithValueGreaterThanMaxComponent { -} +class SliderWithValueGreaterThanMaxComponent {} @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) -class VerticalSliderComponent { -} +class VerticalSliderComponent {} @Component({ template: ` - `, - styles : [ styles ] + + `, + styles: [styles] }) class MixedSliderComponent { range = false; @@ -814,17 +823,16 @@ class MixedSliderComponent { `, - styles : [ styles ] + styles: [styles] }) class SliderWithFormControlComponent implements OnInit { form: FormGroup; - constructor(private fb: FormBuilder) { - } + constructor(private fb: FormBuilder) {} ngOnInit(): void { this.form = this.fb.group({ - slider: [ 42 ] + slider: [42] }); } } @@ -849,8 +857,8 @@ class SliderShowTooltipComponent { function dispatchClickEventSequence(sliderElement: HTMLElement, percentage: number): void { const trackElement = sliderElement.querySelector('.ant-slider-rail')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percentage); - const y = dimensions.top + (dimensions.height * percentage); + const x = dimensions.left + dimensions.width * percentage; + const y = dimensions.top + dimensions.height * percentage; dispatchMouseenterEvent(sliderElement); dispatchMouseEvent(sliderElement, 'mousedown', x, y); @@ -864,8 +872,12 @@ function dispatchClickEventSequence(sliderElement: HTMLElement, percentage: numb * @param endPercent The percentage of the slider where the slide will end. * @param stick Whether stick on and not mouseup when move at the end */ -function dispatchSlideEventSequence(sliderElement: HTMLElement, startPercent: number, - endPercent: number, stick: boolean = false): void { +function dispatchSlideEventSequence( + sliderElement: HTMLElement, + startPercent: number, + endPercent: number, + stick: boolean = false +): void { dispatchMouseenterEvent(sliderElement); dispatchSlideStartEvent(sliderElement, startPercent); dispatchSlideEvent(sliderElement, startPercent); @@ -883,8 +895,8 @@ function dispatchSlideEventSequence(sliderElement: HTMLElement, startPercent: nu function dispatchSlideEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.ant-slider-rail')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mousemove', x, y); } @@ -897,8 +909,8 @@ function dispatchSlideEvent(sliderElement: HTMLElement, percent: number): void { function dispatchSlideStartEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.ant-slider-rail')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseenterEvent(sliderElement); @@ -913,8 +925,8 @@ function dispatchSlideStartEvent(sliderElement: HTMLElement, percent: number): v function dispatchSlideEndEvent(sliderElement: HTMLElement, percent: number): void { const trackElement = sliderElement.querySelector('.ant-slider-rail')!; const dimensions = trackElement.getBoundingClientRect(); - const x = dimensions.left + (dimensions.width * percent); - const y = dimensions.top + (dimensions.height * percent); + const x = dimensions.left + dimensions.width * percent; + const y = dimensions.top + dimensions.height * percent; dispatchMouseEvent(document, 'mouseup', x, y); } diff --git a/components/spin/demo/basic.ts b/components/spin/demo/basic.ts index 8a4e8ad9a5a..30e8f985540 100644 --- a/components/spin/demo/basic.ts +++ b/components/spin/demo/basic.ts @@ -3,7 +3,7 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-spin-basic', template: ` - ` + + ` }) -export class NzDemoSpinBasicComponent { -} +export class NzDemoSpinBasicComponent {} diff --git a/components/spin/demo/custom-indicator.ts b/components/spin/demo/custom-indicator.ts index b40a1d94285..f4d6c8f4c17 100644 --- a/components/spin/demo/custom-indicator.ts +++ b/components/spin/demo/custom-indicator.ts @@ -3,10 +3,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-spin-custom-indicator', template: ` - - - - ` + + + ` }) -export class NzDemoSpinCustomIndicatorComponent { -} +export class NzDemoSpinCustomIndicatorComponent {} diff --git a/components/spin/demo/delayAndDebounce.ts b/components/spin/demo/delayAndDebounce.ts index 7366528e1df..b61cdc245d8 100644 --- a/components/spin/demo/delayAndDebounce.ts +++ b/components/spin/demo/delayAndDebounce.ts @@ -4,7 +4,11 @@ import { Component } from '@angular/core'; selector: 'nz-demo-spin-delayAndDebounce', template: ` - +
    diff --git a/components/spin/demo/inside.ts b/components/spin/demo/inside.ts index a247b6546b5..c8737ec9c16 100644 --- a/components/spin/demo/inside.ts +++ b/components/spin/demo/inside.ts @@ -7,11 +7,11 @@ import { Component } from '@angular/core';
    `, - styles : [ + styles: [ ` .example { text-align: center; - background: rgba(0,0,0,0.05); + background: rgba(0, 0, 0, 0.05); border-radius: 4px; margin-bottom: 20px; padding: 30px 50px; @@ -20,4 +20,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoSpinInsideComponent { } +export class NzDemoSpinInsideComponent {} diff --git a/components/spin/demo/nested.ts b/components/spin/demo/nested.ts index f9f90a5ad1b..1d86481079e 100644 --- a/components/spin/demo/nested.ts +++ b/components/spin/demo/nested.ts @@ -4,7 +4,11 @@ import { Component } from '@angular/core'; selector: 'nz-demo-spin-nested', template: ` - +
    diff --git a/components/spin/demo/size.ts b/components/spin/demo/size.ts index 12957e681b6..c4067fdf0c4 100644 --- a/components/spin/demo/size.ts +++ b/components/spin/demo/size.ts @@ -5,9 +5,10 @@ import { Component } from '@angular/core'; template: ` - `, - styles : [ - ` + + `, + styles: [ + ` nz-spin { display: inline-block; margin-right: 16px; @@ -15,5 +16,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoSpinSizeComponent { -} +export class NzDemoSpinSizeComponent {} diff --git a/components/spin/demo/tip.ts b/components/spin/demo/tip.ts index 0e5d06d1609..b9c15142426 100644 --- a/components/spin/demo/tip.ts +++ b/components/spin/demo/tip.ts @@ -3,13 +3,14 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-spin-tip', template: ` - + + nzDescription="Further details about the context of this alert." + > - ` + + ` }) -export class NzDemoSpinTipComponent { -} +export class NzDemoSpinTipComponent {} diff --git a/components/spin/nz-spin.component.ts b/components/spin/nz-spin.component.ts index b736f3f0f53..d24d2931e07 100644 --- a/components/spin/nz-spin.component.ts +++ b/components/spin/nz-spin.component.ts @@ -1,7 +1,12 @@ import { - ChangeDetectionStrategy, ChangeDetectorRef, + ChangeDetectionStrategy, + ChangeDetectorRef, Component, - Input, OnChanges, OnDestroy, OnInit, SimpleChanges, + Input, + OnChanges, + OnDestroy, + OnInit, + SimpleChanges, TemplateRef, ViewEncapsulation } from '@angular/core'; @@ -12,16 +17,16 @@ import { NzSizeLDSType } from '../core/types/size'; import { InputBoolean, InputNumber } from '../core/util/convert'; @Component({ - selector : 'nz-spin', + selector: 'nz-spin', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-spin.component.html', - host : { + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-spin.component.html', + host: { '[class.ant-spin-nested-loading]': '!nzSimple' }, - styles : [ - ` + styles: [ + ` nz-spin { display: block; } @@ -55,8 +60,7 @@ export class NzSpinComponent implements OnChanges, OnDestroy, OnInit { } } - constructor(private cdr: ChangeDetectorRef) { - } + constructor(private cdr: ChangeDetectorRef) {} ngOnInit(): void { this.subscribeLoading(); diff --git a/components/spin/nz-spin.module.ts b/components/spin/nz-spin.module.ts index c85dc304bac..5ccd3239527 100644 --- a/components/spin/nz-spin.module.ts +++ b/components/spin/nz-spin.module.ts @@ -5,9 +5,8 @@ import { NgModule } from '@angular/core'; import { NzSpinComponent } from './nz-spin.component'; @NgModule({ - exports : [ NzSpinComponent ], - declarations: [ NzSpinComponent ], - imports : [ CommonModule, ObserversModule ] + exports: [NzSpinComponent], + declarations: [NzSpinComponent], + imports: [CommonModule, ObserversModule] }) -export class NzSpinModule { -} +export class NzSpinModule {} diff --git a/components/spin/nz-spin.spec.ts b/components/spin/nz-spin.spec.ts index ad341e458e6..b04c69b9dab 100644 --- a/components/spin/nz-spin.spec.ts +++ b/components/spin/nz-spin.spec.ts @@ -10,8 +10,8 @@ import { NzSpinModule } from './nz-spin.module'; describe('spin', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzSpinModule, NzIconTestModule ], - declarations: [ NzTestSpinBasicComponent ] + imports: [NzSpinModule, NzIconTestModule], + declarations: [NzTestSpinBasicComponent] }); TestBed.compileComponents(); })); @@ -106,17 +106,18 @@ describe('spin', () => { @Component({ selector: 'nz-test-spin-basic', template: ` - - + + [nzIndicator]="indicator" + >
    test
    -
    ` + + ` }) export class NzTestSpinBasicComponent { @ViewChild('indicatorTemplate') indicatorTemplate: TemplateRef; diff --git a/components/statistic/demo/basic.ts b/components/statistic/demo/basic.ts index 90648866be6..3df60cf3ccb 100644 --- a/components/statistic/demo/basic.ts +++ b/components/statistic/demo/basic.ts @@ -8,10 +8,9 @@ import { Component } from '@angular/core'; - + ` }) -export class NzDemoStatisticBasicComponent { -} +export class NzDemoStatisticBasicComponent {} diff --git a/components/statistic/demo/card.ts b/components/statistic/demo/card.ts index 91c5619c1ec..abb5d2927ac 100644 --- a/components/statistic/demo/card.ts +++ b/components/statistic/demo/card.ts @@ -12,7 +12,8 @@ import { Component } from '@angular/core'; [nzTitle]="'Active'" [nzPrefix]="prefixTplOne" [nzSuffix]="'%'" - [nzValueStyle]="{ color: '#3F8600' }"> + [nzValueStyle]="{ color: '#3F8600' }" + > @@ -24,7 +25,8 @@ import { Component } from '@angular/core'; [nzTitle]="'Idle'" [nzPrefix]="prefixTplTwo" [nzSuffix]="'%'" - [nzValueStyle]="{ color: '#CF1322' }"> + [nzValueStyle]="{ color: '#CF1322' }" + > @@ -33,5 +35,4 @@ import { Component } from '@angular/core';
    ` }) -export class NzDemoStatisticCardComponent { -} +export class NzDemoStatisticCardComponent {} diff --git a/components/statistic/demo/unit.ts b/components/statistic/demo/unit.ts index 56188c0a322..ff3bafc90a4 100644 --- a/components/statistic/demo/unit.ts +++ b/components/statistic/demo/unit.ts @@ -14,5 +14,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStatisticUnitComponent { -} +export class NzDemoStatisticUnitComponent {} diff --git a/components/statistic/nz-countdown.component.ts b/components/statistic/nz-countdown.component.ts index 1413518e24d..a485a94e3e8 100644 --- a/components/statistic/nz-countdown.component.ts +++ b/components/statistic/nz-countdown.component.ts @@ -17,9 +17,9 @@ import { NzStatisticComponent } from './nz-statistic.component'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-countdown', - templateUrl : './nz-countdown.component.html' + encapsulation: ViewEncapsulation.None, + selector: 'nz-countdown', + templateUrl: './nz-countdown.component.html' }) export class NzCountdownComponent extends NzStatisticComponent implements OnInit, OnChanges, OnDestroy { /** @override */ diff --git a/components/statistic/nz-countdown.spec.ts b/components/statistic/nz-countdown.spec.ts index 28198411057..8857bfbc311 100644 --- a/components/statistic/nz-countdown.spec.ts +++ b/components/statistic/nz-countdown.spec.ts @@ -12,8 +12,8 @@ describe('nz-countdown', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzStatisticModule ], - declarations: [ NzTestCountdownComponent ] + imports: [CommonModule, NzStatisticModule], + declarations: [NzTestCountdownComponent] }).compileComponents(); }); @@ -60,11 +60,7 @@ describe('nz-countdown', () => { @Component({ selector: 'nz-test', template: ` - + {{ diff }} diff --git a/components/statistic/nz-statistic-number.component.ts b/components/statistic/nz-statistic-number.component.ts index 5c619405975..5d3a412ad83 100644 --- a/components/statistic/nz-statistic-number.component.ts +++ b/components/statistic/nz-statistic-number.component.ts @@ -12,15 +12,15 @@ import { import { NzStatisticValueType } from './nz-statistic-definitions'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - selector : 'nz-statistic-number', - templateUrl : './nz-statistic-number.component.html', - host : { - 'class': 'ant-statistic-content-value' + selector: 'nz-statistic-number', + templateUrl: './nz-statistic-number.component.html', + host: { + class: 'ant-statistic-content-value' }, - styles : [ 'nz-number { display: inline }' ] + styles: ['nz-number { display: inline }'] }) export class NzStatisticNumberComponent implements OnChanges { @Input() nzValue: NzStatisticValueType; @@ -36,11 +36,10 @@ export class NzStatisticNumberComponent implements OnChanges { } private formatNumber(): void { - const decimalSeparator: string = typeof this.nzValue === 'number' - ? '.' - : getLocaleNumberSymbol(this.locale_id, NumberSymbol.Decimal); + const decimalSeparator: string = + typeof this.nzValue === 'number' ? '.' : getLocaleNumberSymbol(this.locale_id, NumberSymbol.Decimal); const value = String(this.nzValue); - const [ int, decimal ] = value.split(decimalSeparator); + const [int, decimal] = value.split(decimalSeparator); this.displayInt = int; this.displayDecimal = decimal ? `${decimalSeparator}${decimal}` : ''; diff --git a/components/statistic/nz-statistic-number.spec.ts b/components/statistic/nz-statistic-number.spec.ts index 83120fd5dab..9c145d9e9ef 100644 --- a/components/statistic/nz-statistic-number.spec.ts +++ b/components/statistic/nz-statistic-number.spec.ts @@ -12,8 +12,8 @@ describe('nz-number', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzStatisticModule ], - declarations: [ NzTestNumberComponent ] + imports: [CommonModule, NzStatisticModule], + declarations: [NzTestNumberComponent] }).compileComponents(); }); @@ -43,7 +43,7 @@ describe('nz-number', () => { fixture.detectChanges(); expect(numberEl.nativeElement.querySelector('.ant-statistic-content-value-int')).toBeFalsy(); expect(numberEl.nativeElement.querySelector('.ant-statistic-content-value-decimal')).toBeFalsy(); - expect(numberEl.nativeElement.innerText).toBe('It\'s 12,345.012'); + expect(numberEl.nativeElement.innerText).toBe("It's 12,345.012"); }); }); }); diff --git a/components/statistic/nz-statistic.component.ts b/components/statistic/nz-statistic.component.ts index 81a32b46a26..01b7922b85a 100644 --- a/components/statistic/nz-statistic.component.ts +++ b/components/statistic/nz-statistic.component.ts @@ -1,21 +1,15 @@ -import { - ChangeDetectionStrategy, - Component, - Input, - TemplateRef, - ViewEncapsulation -} from '@angular/core'; +import { ChangeDetectionStrategy, Component, Input, TemplateRef, ViewEncapsulation } from '@angular/core'; import { NzStatisticValueType } from './nz-statistic-definitions'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-statistic', - templateUrl : './nz-statistic.component.html', - host : { + encapsulation: ViewEncapsulation.None, + selector: 'nz-statistic', + templateUrl: './nz-statistic.component.html', + host: { class: 'ant-statistic' }, - styles : [ 'nz-statistic { display: block; }' ] + styles: ['nz-statistic { display: block; }'] }) export class NzStatisticComponent { @Input() nzPrefix: string | TemplateRef; diff --git a/components/statistic/nz-statistic.module.ts b/components/statistic/nz-statistic.module.ts index 76b497ef2f6..687841af8dd 100644 --- a/components/statistic/nz-statistic.module.ts +++ b/components/statistic/nz-statistic.module.ts @@ -8,9 +8,8 @@ import { NzStatisticComponent } from './nz-statistic.component'; import { NzTimeRangePipe } from './nz-time-range.pipe'; @NgModule({ - imports : [ CommonModule, NzAddOnModule ], - declarations: [ NzStatisticComponent, NzCountdownComponent, NzStatisticNumberComponent, NzTimeRangePipe ], - exports : [ NzStatisticComponent, NzCountdownComponent, NzStatisticNumberComponent, NzTimeRangePipe ] + imports: [CommonModule, NzAddOnModule], + declarations: [NzStatisticComponent, NzCountdownComponent, NzStatisticNumberComponent, NzTimeRangePipe], + exports: [NzStatisticComponent, NzCountdownComponent, NzStatisticNumberComponent, NzTimeRangePipe] }) -export class NzStatisticModule { -} +export class NzStatisticModule {} diff --git a/components/statistic/nz-statistic.spec.ts b/components/statistic/nz-statistic.spec.ts index 5e4446bfe7a..88ca82f2696 100644 --- a/components/statistic/nz-statistic.spec.ts +++ b/components/statistic/nz-statistic.spec.ts @@ -12,8 +12,8 @@ describe('nz-statistic', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzStatisticModule ], - declarations: [ NzTestStatisticComponent ] + imports: [CommonModule, NzStatisticModule], + declarations: [NzTestStatisticComponent] }).compileComponents(); }); @@ -42,12 +42,7 @@ describe('nz-statistic', () => { @Component({ selector: 'nz-test-statistic', template: ` - - + ` }) export class NzTestStatisticComponent { diff --git a/components/statistic/nz-time-range.pipe.ts b/components/statistic/nz-time-range.pipe.ts index afc749e1594..aca1c1c2a7f 100644 --- a/components/statistic/nz-time-range.pipe.ts +++ b/components/statistic/nz-time-range.pipe.ts @@ -9,16 +9,13 @@ export class NzTimeRangePipe implements PipeTransform { transform(value: string | number, format: string = 'HH:mm:ss'): string { let duration = Number(value || 0); - return timeUnits.reduce((current, [ name, unit ]) => { + return timeUnits.reduce((current, [name, unit]) => { if (current.indexOf(name) !== -1) { const v = Math.floor(duration / unit); duration -= v * unit; - return current.replace( - new RegExp(`${name}+`, 'g'), - (match: string) => { - return padStart(v.toString(), match.length, '0'); - } - ); + return current.replace(new RegExp(`${name}+`, 'g'), (match: string) => { + return padStart(v.toString(), match.length, '0'); + }); } return current; }, format); diff --git a/components/statistic/nz-time-range.spec.ts b/components/statistic/nz-time-range.spec.ts index bfd453e42e9..df9c5079903 100644 --- a/components/statistic/nz-time-range.spec.ts +++ b/components/statistic/nz-time-range.spec.ts @@ -10,8 +10,8 @@ describe('nz time range pipeline', () => { beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, NzStatisticModule ], - declarations: [ NzTestTimeRangeComponent ] + imports: [CommonModule, NzStatisticModule], + declarations: [NzTestTimeRangeComponent] }).compileComponents(); }); @@ -40,7 +40,7 @@ describe('nz time range pipeline', () => { fixture.detectChanges(); expect(element.innerText).toBe('00:00:00'); - testComponent.diff = - 1000 * 60 * 60 * 24 * 2 + 1000 * 30; + testComponent.diff = -1000 * 60 * 60 * 24 * 2 + 1000 * 30; fixture.detectChanges(); expect(element.innerText).toBe('-48:00:30'); }); @@ -49,7 +49,9 @@ describe('nz time range pipeline', () => { @Component({ selector: 'nz-test-statistic', - template: `{{ diff | nzTimeRange: format }}` + template: ` + {{ diff | nzTimeRange: format }} + ` }) export class NzTestTimeRangeComponent { diff = 1000 * 60 * 60 * 24 * 2 + 1000 * 30; diff --git a/components/steps/demo/customized-progress-dot.ts b/components/steps/demo/customized-progress-dot.ts index a5ec9f2f5d9..ee6573387eb 100644 --- a/components/steps/demo/customized-progress-dot.ts +++ b/components/steps/demo/customized-progress-dot.ts @@ -10,7 +10,7 @@ import { Component } from '@angular/core'; - + @@ -18,5 +18,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsCustomizedProgressDotComponent { -} +export class NzDemoStepsCustomizedProgressDotComponent {} diff --git a/components/steps/demo/error.ts b/components/steps/demo/error.ts index 66b2e0e2f13..5ae08972479 100644 --- a/components/steps/demo/error.ts +++ b/components/steps/demo/error.ts @@ -10,5 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsErrorComponent { -} +export class NzDemoStepsErrorComponent {} diff --git a/components/steps/demo/icon.ts b/components/steps/demo/icon.ts index 3dab2b93912..a18cca1046c 100644 --- a/components/steps/demo/icon.ts +++ b/components/steps/demo/icon.ts @@ -12,5 +12,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsIconComponent { -} +export class NzDemoStepsIconComponent {} diff --git a/components/steps/demo/progress-dot.ts b/components/steps/demo/progress-dot.ts index 34ab25cc207..63f8a42b29f 100644 --- a/components/steps/demo/progress-dot.ts +++ b/components/steps/demo/progress-dot.ts @@ -10,5 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsProgressDotComponent { -} +export class NzDemoStepsProgressDotComponent {} diff --git a/components/steps/demo/simple.ts b/components/steps/demo/simple.ts index 64cc4daa83b..1667642e86a 100644 --- a/components/steps/demo/simple.ts +++ b/components/steps/demo/simple.ts @@ -10,5 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsSimpleComponent { -} +export class NzDemoStepsSimpleComponent {} diff --git a/components/steps/demo/step-next.ts b/components/steps/demo/step-next.ts index 2237eef20d0..4a569679f61 100644 --- a/components/steps/demo/step-next.ts +++ b/components/steps/demo/step-next.ts @@ -22,8 +22,8 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` .steps-content { margin-top: 16px; border: 1px dashed #e9e9e9; @@ -83,6 +83,5 @@ export class NzDemoStepsStepNextComponent { } } - constructor() { - } + constructor() {} } diff --git a/components/steps/demo/vertical-small.ts b/components/steps/demo/vertical-small.ts index 98c48b9e1f1..23fec46b6f4 100644 --- a/components/steps/demo/vertical-small.ts +++ b/components/steps/demo/vertical-small.ts @@ -10,5 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsVerticalSmallComponent { -} +export class NzDemoStepsVerticalSmallComponent {} diff --git a/components/steps/demo/vertical.ts b/components/steps/demo/vertical.ts index 4dea3077cc4..13d89b65df1 100644 --- a/components/steps/demo/vertical.ts +++ b/components/steps/demo/vertical.ts @@ -10,5 +10,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoStepsVerticalComponent { -} +export class NzDemoStepsVerticalComponent {} diff --git a/components/steps/nz-step.component.ts b/components/steps/nz-step.component.ts index 9abe2f6ffab..2101de68005 100644 --- a/components/steps/nz-step.component.ts +++ b/components/steps/nz-step.component.ts @@ -1,7 +1,8 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, + Component, + ElementRef, Input, Renderer2, TemplateRef, @@ -12,18 +13,18 @@ import { import { NgClassType } from '../core/types/ng-class'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - selector : 'nz-step', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + selector: 'nz-step', preserveWhitespaces: false, - templateUrl : './nz-step.component.html', - host : { - '[class.ant-steps-item-wait]' : 'nzStatus === "wait"', + templateUrl: './nz-step.component.html', + host: { + '[class.ant-steps-item-wait]': 'nzStatus === "wait"', '[class.ant-steps-item-process]': 'nzStatus === "process"', - '[class.ant-steps-item-finish]' : 'nzStatus === "finish"', - '[class.ant-steps-item-error]' : 'nzStatus === "error"', - '[class.ant-steps-custom]' : '!!nzIcon', - '[class.ant-steps-next-error]' : '(outStatus === "error") && (currentIndex === index + 1)' + '[class.ant-steps-item-finish]': 'nzStatus === "finish"', + '[class.ant-steps-item-error]': 'nzStatus === "error"', + '[class.ant-steps-custom]': '!!nzIcon', + '[class.ant-steps-next-error]': '(outStatus === "error") && (currentIndex === index + 1)' } }) export class NzStepComponent { @@ -64,7 +65,7 @@ export class NzStepComponent { isIconString = true; private _icon: NgClassType | TemplateRef; - customProcessTemplate: TemplateRef<{ $implicit: TemplateRef, status: string, index: number }>; // Set by parent. + customProcessTemplate: TemplateRef<{ $implicit: TemplateRef; status: string; index: number }>; // Set by parent. direction = 'horizontal'; index = 0; last = false; @@ -78,11 +79,7 @@ export class NzStepComponent { set currentIndex(current: number) { this._currentIndex = current; if (!this.isCustomStatus) { - this._status = current > this.index - ? 'finish' - : current === this.index - ? this.outStatus || '' - : 'wait'; + this._status = current > this.index ? 'finish' : current === this.index ? this.outStatus || '' : 'wait'; } } diff --git a/components/steps/nz-steps.component.ts b/components/steps/nz-steps.component.ts index 675df686485..038146afaee 100644 --- a/components/steps/nz-steps.component.ts +++ b/components/steps/nz-steps.component.ts @@ -25,11 +25,11 @@ export type NzDirectionType = 'horizontal' | 'vertical'; export type NzStatusType = 'wait' | 'process' | 'finish' | 'error'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - selector : 'nz-steps', - templateUrl : './nz-steps.component.html' + selector: 'nz-steps', + templateUrl: './nz-steps.component.html' }) export class NzStepsComponent implements OnChanges, OnInit, OnDestroy, AfterContentInit { @ContentChildren(NzStepComponent) steps: QueryList; @@ -42,7 +42,7 @@ export class NzStepsComponent implements OnChanges, OnInit, OnDestroy, AfterCont @Input() nzStatus: NzStatusType = 'process'; @Input() - set nzProgressDot(value: boolean | TemplateRef<{ $implicit: TemplateRef, status: string, index: number }>) { + set nzProgressDot(value: boolean | TemplateRef<{ $implicit: TemplateRef; status: string; index: number }>) { if (value instanceof TemplateRef) { this.showProcessDot = true; this.customProcessDotTemplate = value; @@ -52,7 +52,7 @@ export class NzStepsComponent implements OnChanges, OnInit, OnDestroy, AfterCont this.updateChildrenSteps(); } showProcessDot = false; - customProcessDotTemplate: TemplateRef<{ $implicit: TemplateRef, status: string, index: number }>; + customProcessDotTemplate: TemplateRef<{ $implicit: TemplateRef; status: string; index: number }>; classMap: NgClassType; @@ -106,11 +106,12 @@ export class NzStepsComponent implements OnChanges, OnInit, OnDestroy, AfterCont private setClassMap(): void { this.classMap = { - [ `ant-steps-${this.nzDirection}` ]: true, - [ `ant-steps-label-horizontal` ] : this.nzDirection === 'horizontal', - [ `ant-steps-label-vertical` ] : (this.showProcessDot || this.nzLabelPlacement === 'vertical') && this.nzDirection === 'horizontal', - [ `ant-steps-dot` ] : this.showProcessDot, - [ 'ant-steps-small' ] : this.nzSize === 'small' + [`ant-steps-${this.nzDirection}`]: true, + [`ant-steps-label-horizontal`]: this.nzDirection === 'horizontal', + [`ant-steps-label-vertical`]: + (this.showProcessDot || this.nzLabelPlacement === 'vertical') && this.nzDirection === 'horizontal', + [`ant-steps-dot`]: this.showProcessDot, + ['ant-steps-small']: this.nzSize === 'small' }; } } diff --git a/components/steps/nz-steps.module.ts b/components/steps/nz-steps.module.ts index 25319376f2e..1a01d1cff1d 100644 --- a/components/steps/nz-steps.module.ts +++ b/components/steps/nz-steps.module.ts @@ -8,9 +8,8 @@ import { NzStepComponent } from './nz-step.component'; import { NzStepsComponent } from './nz-steps.component'; @NgModule({ - imports : [ CommonModule, NzIconModule, NzAddOnModule ], - exports : [ NzStepsComponent, NzStepComponent ], - declarations: [ NzStepsComponent, NzStepComponent ] + imports: [CommonModule, NzIconModule, NzAddOnModule], + exports: [NzStepsComponent, NzStepComponent], + declarations: [NzStepsComponent, NzStepComponent] }) -export class NzStepsModule { -} +export class NzStepsModule {} diff --git a/components/steps/nz-steps.spec.ts b/components/steps/nz-steps.spec.ts index 2f694c4c5e2..047e1b13279 100644 --- a/components/steps/nz-steps.spec.ts +++ b/components/steps/nz-steps.spec.ts @@ -1,4 +1,11 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DebugElement, TemplateRef, ViewChild } from '@angular/core'; +import { + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + DebugElement, + TemplateRef, + ViewChild +} from '@angular/core'; import { async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; @@ -11,8 +18,13 @@ import { NzStepsModule } from './nz-steps.module'; describe('steps', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzStepsModule, NzIconTestModule ], - declarations: [ NzTestOuterStepsComponent, NzTestInnerStepStringComponent, NzTestInnerStepTemplateComponent, NzTestStepForComponent ] + imports: [NzStepsModule, NzIconTestModule], + declarations: [ + NzTestOuterStepsComponent, + NzTestInnerStepStringComponent, + NzTestInnerStepTemplateComponent, + NzTestStepForComponent + ] }); TestBed.compileComponents(); })); @@ -32,10 +44,12 @@ describe('steps', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(outStep.nativeElement.firstElementChild.className).toBe('ant-steps ant-steps-horizontal ant-steps-label-horizontal'); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); - expect(innerSteps[ 2 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(outStep.nativeElement.firstElementChild.className).toBe( + 'ant-steps ant-steps-horizontal ant-steps-label-horizontal' + ); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(innerSteps[2].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); })); it('should current change correct', fakeAsync(() => { fixture.detectChanges(); @@ -46,42 +60,62 @@ describe('steps', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish'); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); - expect(innerSteps[ 2 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); + expect(innerSteps[2].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); })); it('should tail display correct', fakeAsync(() => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(true); - expect(innerSteps[ 1 ].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(true); - expect(innerSteps[ 2 ].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(false); + expect(innerSteps[0].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(true); + expect(innerSteps[1].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(true); + expect(innerSteps[2].nativeElement.firstElementChild!.classList.contains('ant-steps-item-tail')).toBe(false); })); it('should title correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('0title'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('1title'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('2title'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('0title'); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('1title'); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('2title'); }); it('should description correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('0description'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('1description'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('2description'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + '0description' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + '1description' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + '2description' + ); }); it('should icon display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-icon').firstElementChild!.classList.contains('ant-steps-icon')).toBe(true); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-icon').firstElementChild!.classList.contains('ant-steps-icon')).toBe(true); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-icon').firstElementChild!.classList.contains('ant-steps-icon')).toBe(true); + expect( + innerSteps[0].nativeElement + .querySelector('.ant-steps-item-icon') + .firstElementChild!.classList.contains('ant-steps-icon') + ).toBe(true); + expect( + innerSteps[1].nativeElement + .querySelector('.ant-steps-item-icon') + .firstElementChild!.classList.contains('ant-steps-icon') + ).toBe(true); + expect( + innerSteps[2].nativeElement + .querySelector('.ant-steps-item-icon') + .firstElementChild!.classList.contains('ant-steps-icon') + ).toBe(true); }); it('should size display correct', () => { fixture.detectChanges(); testComponent.size = 'small'; testComponent.cdr.markForCheck(); fixture.detectChanges(); - expect(outStep.nativeElement.firstElementChild.className).toBe('ant-steps ant-steps-horizontal ant-steps-label-horizontal ant-steps-small'); + expect(outStep.nativeElement.firstElementChild.className).toBe( + 'ant-steps ant-steps-horizontal ant-steps-label-horizontal ant-steps-small' + ); }); it('should direction display correct', () => { fixture.detectChanges(); @@ -106,21 +140,21 @@ describe('steps', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); testComponent.status = 'finish'; testComponent.cdr.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish'); testComponent.status = 'error'; testComponent.current = 1; testComponent.cdr.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-error'); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish ant-steps-next-error'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-item-error'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-finish ant-steps-next-error'); })); it('should processDot display correct', fakeAsync(() => { fixture.detectChanges(); @@ -132,9 +166,21 @@ describe('steps', () => { tick(); fixture.detectChanges(); expect(outStep.nativeElement.firstElementChild!.classList.contains('ant-steps-dot')).toBe(true); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild!.classList.contains('ant-steps-icon-dot')).toBe(true); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild!.classList.contains('ant-steps-icon-dot')).toBe(true); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild!.classList.contains('ant-steps-icon-dot')).toBe(true); + expect( + innerSteps[0].nativeElement + .querySelector('.ant-steps-icon') + .firstElementChild!.classList.contains('ant-steps-icon-dot') + ).toBe(true); + expect( + innerSteps[1].nativeElement + .querySelector('.ant-steps-icon') + .firstElementChild!.classList.contains('ant-steps-icon-dot') + ).toBe(true); + expect( + innerSteps[2].nativeElement + .querySelector('.ant-steps-icon') + .firstElementChild!.classList.contains('ant-steps-icon-dot') + ).toBe(true); })); it('should processDot template display correct', fakeAsync(() => { fixture.detectChanges(); @@ -146,12 +192,30 @@ describe('steps', () => { tick(); fixture.detectChanges(); expect(outStep.nativeElement.firstElementChild!.classList.contains('ant-steps-dot')).toBe(true); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe('process0'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe('wait1'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe('wait2'); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').lastElementChild.classList.contains('ant-steps-icon-dot')).toBe(true); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').lastElementChild.classList.contains('ant-steps-icon-dot')).toBe(true); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').lastElementChild.classList.contains('ant-steps-icon-dot')).toBe(true); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe( + 'process0' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe( + 'wait1' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-icon').firstElementChild.innerText.trim()).toBe( + 'wait2' + ); + expect( + innerSteps[0].nativeElement + .querySelector('.ant-steps-icon') + .lastElementChild.classList.contains('ant-steps-icon-dot') + ).toBe(true); + expect( + innerSteps[1].nativeElement + .querySelector('.ant-steps-icon') + .lastElementChild.classList.contains('ant-steps-icon-dot') + ).toBe(true); + expect( + innerSteps[2].nativeElement + .querySelector('.ant-steps-icon') + .lastElementChild.classList.contains('ant-steps-icon-dot') + ).toBe(true); })); it('should support custom starting index', fakeAsync(() => { fixture.detectChanges(); @@ -163,12 +227,12 @@ describe('steps', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); - expect(innerSteps[ 2 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('4'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('5'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('6'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-process'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(innerSteps[2].nativeElement.className).toBe('ant-steps-item ant-steps-item-wait'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('4'); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('5'); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-icon').innerText.trim()).toBe('6'); })); }); describe('inner step string', () => { @@ -183,32 +247,44 @@ describe('steps', () => { }); it('should status display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); - expect(innerSteps[ 2 ].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); + expect(innerSteps[2].nativeElement.className).toBe('ant-steps-item ant-steps-item-process ant-steps-custom'); testComponent.status = 'wait'; fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); - expect(innerSteps[ 1 ].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); - expect(innerSteps[ 2 ].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); + expect(innerSteps[0].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); + expect(innerSteps[1].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); + expect(innerSteps[2].nativeElement.className).toBe('ant-steps-item ant-steps-custom ant-steps-item-wait'); }); it('should title display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('title'); }); it('should description display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('description'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('description'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('description'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'description' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'description' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'description' + ); }); it('should icon display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe('anticon anticon-user'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe('anticon anticon-user'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe('anticon anticon-user'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe( + 'anticon anticon-user' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe( + 'anticon anticon-user' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toBe( + 'anticon anticon-user' + ); }); }); describe('inner step template', () => { @@ -221,21 +297,33 @@ describe('steps', () => { }); it('should title display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-title').innerText.trim()).toBe('titleTemplate'); }); it('should description display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('descriptionTemplate'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('descriptionTemplate'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe('descriptionTemplate'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'descriptionTemplate' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'descriptionTemplate' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-item-description').innerText.trim()).toBe( + 'descriptionTemplate' + ); }); it('should icon display correct', () => { fixture.detectChanges(); - expect(innerSteps[ 0 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain('anticon-smile-o'); - expect(innerSteps[ 1 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain('anticon-smile-o'); - expect(innerSteps[ 2 ].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain('anticon-smile-o'); + expect(innerSteps[0].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain( + 'anticon-smile-o' + ); + expect(innerSteps[1].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain( + 'anticon-smile-o' + ); + expect(innerSteps[2].nativeElement.querySelector('.ant-steps-icon').firstElementChild.className).toContain( + 'anticon-smile-o' + ); }); }); describe('step ng for', () => { @@ -254,14 +342,21 @@ describe('steps', () => { @Component({ selector: 'nz-test-outer-steps', template: ` - + - {{status}}{{index}} + {{ status }}{{ index }} `, @@ -276,7 +371,7 @@ export class NzTestOuterStepsComponent { status = 'process'; progressDot: boolean | TemplateRef = false; startIndex = 0; - constructor (public cdr: ChangeDetectorRef) {} + constructor(public cdr: ChangeDetectorRef) {} } @Component({ @@ -316,19 +411,18 @@ export class NzTestInnerStepStringComponent { ` }) -export class NzTestInnerStepTemplateComponent { -} +export class NzTestInnerStepTemplateComponent {} @Component({ selector: 'nz-test-step-for', template: ` - + ` }) export class NzTestStepForComponent { - steps = [ 1, 2, 3 ]; + steps = [1, 2, 3]; trackById(index: number): number { return index; diff --git a/components/switch/demo/basic.ts b/components/switch/demo/basic.ts index 9312e3b2c4c..ccb7e5fe748 100755 --- a/components/switch/demo/basic.ts +++ b/components/switch/demo/basic.ts @@ -2,7 +2,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-switch-basic', - template: `` + template: ` + + ` }) export class NzDemoSwitchBasicComponent { switchValue = false; diff --git a/components/switch/demo/control.ts b/components/switch/demo/control.ts index 76eff8ebfa5..ab879b9834b 100755 --- a/components/switch/demo/control.ts +++ b/components/switch/demo/control.ts @@ -2,7 +2,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-switch-control', - template: `` + template: ` + + ` }) export class NzDemoSwitchControlComponent { switchValue = false; @@ -16,6 +18,5 @@ export class NzDemoSwitchControlComponent { this.loading = false; }, 3000); } - } } diff --git a/components/switch/demo/disabled.ts b/components/switch/demo/disabled.ts index 0e21051e25a..2df457408c7 100755 --- a/components/switch/demo/disabled.ts +++ b/components/switch/demo/disabled.ts @@ -4,12 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-switch-disabled', template: ` -
    - `, - styles : [ ` - nz-switch { - margin-bottom: 8px; - }` +
    + + `, + styles: [ + ` + nz-switch { + margin-bottom: 8px; + } + ` ] }) export class NzDemoSwitchDisabledComponent { diff --git a/components/switch/demo/loading.ts b/components/switch/demo/loading.ts index 7ac7c9fe582..e08c197f42c 100755 --- a/components/switch/demo/loading.ts +++ b/components/switch/demo/loading.ts @@ -4,14 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-switch-loading', template: ` -
    +
    `, - styles : [ ` - nz-switch { - margin-bottom: 8px; - }` + styles: [ + ` + nz-switch { + margin-bottom: 8px; + } + ` ] }) -export class NzDemoSwitchLoadingComponent { -} +export class NzDemoSwitchLoadingComponent {} diff --git a/components/switch/demo/size.ts b/components/switch/demo/size.ts index 88047b86392..db5c73a7013 100755 --- a/components/switch/demo/size.ts +++ b/components/switch/demo/size.ts @@ -4,14 +4,15 @@ import { Component } from '@angular/core'; selector: 'nz-demo-switch-size', template: ` -
    +
    `, - styles : [ ` - nz-switch { - margin-bottom: 8px; - }` + styles: [ + ` + nz-switch { + margin-bottom: 8px; + } + ` ] }) -export class NzDemoSwitchSizeComponent { -} +export class NzDemoSwitchSizeComponent {} diff --git a/components/switch/demo/text.ts b/components/switch/demo/text.ts index a5ae992ec36..fae3dfbf694 100755 --- a/components/switch/demo/text.ts +++ b/components/switch/demo/text.ts @@ -4,18 +4,23 @@ import { Component } from '@angular/core'; selector: 'nz-demo-switch-text', template: ` -
    +
    -
    - +
    + `, - styles : [ ` - nz-switch { - margin-bottom: 8px; - }` + styles: [ + ` + nz-switch { + margin-bottom: 8px; + } + ` ] }) -export class NzDemoSwitchTextComponent { -} +export class NzDemoSwitchTextComponent {} diff --git a/components/switch/nz-switch.component.ts b/components/switch/nz-switch.component.ts index b194cdf6724..a3539c272e8 100644 --- a/components/switch/nz-switch.component.ts +++ b/components/switch/nz-switch.component.ts @@ -18,25 +18,27 @@ import { NzSizeDSType } from '../core/types/size'; import { InputBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-switch', + selector: 'nz-switch', preserveWhitespaces: false, - templateUrl : './nz-switch.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - providers : [ + templateUrl: './nz-switch.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + providers: [ { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzSwitchComponent), - multi : true + multi: true } ], - host : { + host: { '(click)': 'hostClick($event)' }, - styles : [ ` - nz-switch { - display: inline-block; - }` + styles: [ + ` + nz-switch { + display: inline-block; + } + ` ] }) export class NzSwitchComponent implements ControlValueAccessor, AfterViewInit { @@ -88,8 +90,7 @@ export class NzSwitchComponent implements ControlValueAccessor, AfterViewInit { this.switchElement.nativeElement.blur(); } - constructor(private cdr: ChangeDetectorRef, private focusMonitor: FocusMonitor) { - } + constructor(private cdr: ChangeDetectorRef, private focusMonitor: FocusMonitor) {} ngAfterViewInit(): void { this.focusMonitor.monitor(this.switchElement.nativeElement, true).subscribe(focusOrigin => { diff --git a/components/switch/nz-switch.module.ts b/components/switch/nz-switch.module.ts index e54d2b8c701..95ce1f9b8b2 100644 --- a/components/switch/nz-switch.module.ts +++ b/components/switch/nz-switch.module.ts @@ -7,9 +7,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzSwitchComponent } from './nz-switch.component'; @NgModule({ - exports : [ NzSwitchComponent ], - declarations: [ NzSwitchComponent ], - imports : [ CommonModule, NzWaveModule, NzIconModule, NzAddOnModule ] + exports: [NzSwitchComponent], + declarations: [NzSwitchComponent], + imports: [CommonModule, NzWaveModule, NzIconModule, NzAddOnModule] }) -export class NzSwitchModule { -} +export class NzSwitchModule {} diff --git a/components/switch/nz-switch.spec.ts b/components/switch/nz-switch.spec.ts index 30a06a25500..14c8a901048 100644 --- a/components/switch/nz-switch.spec.ts +++ b/components/switch/nz-switch.spec.ts @@ -13,8 +13,8 @@ import { NzSwitchModule } from './nz-switch.module'; describe('switch', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzSwitchModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ NzTestSwitchBasicComponent, NzTestSwitchFormComponent, NzTestSwitchTemplateComponent ] + imports: [NzSwitchModule, FormsModule, ReactiveFormsModule, NzIconTestModule], + declarations: [NzTestSwitchBasicComponent, NzTestSwitchFormComponent, NzTestSwitchTemplateComponent] }); TestBed.compileComponents(); })); @@ -177,12 +177,16 @@ describe('switch', () => { fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(switchElement.nativeElement.firstElementChild.firstElementChild.firstElementChild.firstElementChild!.classList).toContain('anticon-close'); + expect( + switchElement.nativeElement.firstElementChild.firstElementChild.firstElementChild.firstElementChild!.classList + ).toContain('anticon-close'); switchElement.nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); - expect(switchElement.nativeElement.firstElementChild.firstElementChild.firstElementChild.firstElementChild!.classList).toContain('anticon-check'); + expect( + switchElement.nativeElement.firstElementChild.firstElementChild.firstElementChild.firstElementChild!.classList + ).toContain('anticon-check'); })); }); describe('switch form', () => { @@ -238,8 +242,10 @@ describe('switch', () => { [nzSize]="size" [nzControl]="control" [nzCheckedChildren]="checkedChildren" - [nzUnCheckedChildren]="unCheckedChildren"> - ` + [nzUnCheckedChildren]="unCheckedChildren" + > + + ` }) export class NzTestSwitchBasicComponent { @ViewChild(NzSwitchComponent) nzSwitchComponent: NzSwitchComponent; @@ -260,13 +266,11 @@ export class NzTestSwitchBasicComponent { template: ` - - ` + + + ` }) -export class NzTestSwitchTemplateComponent { -} +export class NzTestSwitchTemplateComponent {} @Component({ selector: 'nz-test-switch-form', @@ -281,7 +285,7 @@ export class NzTestSwitchFormComponent { constructor(private formBuilder: FormBuilder) { this.formGroup = this.formBuilder.group({ - switchValue: [ true ] + switchValue: [true] }); } diff --git a/components/table/demo/ajax.ts b/components/table/demo/ajax.ts index 246f67e651a..3ae19a46553 100644 --- a/components/table/demo/ajax.ts +++ b/components/table/demo/ajax.ts @@ -6,12 +6,18 @@ import { Observable } from 'rxjs'; export class RandomUserService { randomUserUrl = 'https://api.randomuser.me/'; - getUsers(pageIndex: number = 1, pageSize: number = 10, sortField: string, sortOrder: string, genders: string[]): Observable<{}> { + getUsers( + pageIndex: number = 1, + pageSize: number = 10, + sortField: string, + sortOrder: string, + genders: string[] + ): Observable<{}> { let params = new HttpParams() - .append('page', `${pageIndex}`) - .append('results', `${pageSize}`) - .append('sortField', sortField) - .append('sortOrder', sortOrder); + .append('page', `${pageIndex}`) + .append('results', `${pageSize}`) + .append('sortField', sortField) + .append('sortOrder', sortOrder); genders.forEach(gender => { params = params.append('gender', gender); }); @@ -20,14 +26,13 @@ export class RandomUserService { }); } - constructor(private http: HttpClient) { - } + constructor(private http: HttpClient) {} } @Component({ - selector : 'nz-demo-table-ajax', - providers: [ RandomUserService ], - template : ` + selector: 'nz-demo-table-ajax', + providers: [RandomUserService], + template: ` + (nzPageSizeChange)="searchData(true)" + > Name @@ -48,12 +54,13 @@ export class RandomUserService { - {{data.name.first}} {{data.name.last}} - {{data.gender}} - {{data.email}} + {{ data.name.first }} {{ data.name.last }} + {{ data.gender }} + {{ data.email }} - ` + + ` }) export class NzDemoTableAjaxComponent implements OnInit { pageIndex = 1; @@ -63,31 +70,29 @@ export class NzDemoTableAjaxComponent implements OnInit { loading = true; sortValue: string | null = null; sortKey: string | null = null; - filterGender = [ - { text: 'male', value: 'male' }, - { text: 'female', value: 'female' } - ]; + filterGender = [{ text: 'male', value: 'male' }, { text: 'female', value: 'female' }]; searchGenderList: string[] = []; - sort(sort: { key: string, value: string }): void { + sort(sort: { key: string; value: string }): void { this.sortKey = sort.key; this.sortValue = sort.value; this.searchData(); } - constructor(private randomUserService: RandomUserService) { - } + constructor(private randomUserService: RandomUserService) {} searchData(reset: boolean = false): void { if (reset) { this.pageIndex = 1; } this.loading = true; - this.randomUserService.getUsers(this.pageIndex, this.pageSize, this.sortKey!, this.sortValue!, this.searchGenderList).subscribe((data: any) => { - this.loading = false; - this.total = 200; - this.listOfData = data.results; - }); + this.randomUserService + .getUsers(this.pageIndex, this.pageSize, this.sortKey!, this.sortValue!, this.searchGenderList) + .subscribe((data: any) => { + this.loading = false; + this.total = 200; + this.listOfData = data.results; + }); } updateFilter(value: string[]): void { diff --git a/components/table/demo/basic.ts b/components/table/demo/basic.ts index e3cbb93ac12..3e9d4528861 100644 --- a/components/table/demo/basic.ts +++ b/components/table/demo/basic.ts @@ -14,11 +14,11 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - Action 一 {{data.name}} + Action 一 {{ data.name }} Delete @@ -30,21 +30,21 @@ import { Component } from '@angular/core'; export class NzDemoTableBasicComponent { listOfData = [ { - key : '1', - name : 'John Brown', - age : 32, + key: '1', + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - key : '2', - name : 'Jim Green', - age : 42, + key: '2', + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - key : '3', - name : 'Joe Black', - age : 32, + key: '3', + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' } ]; diff --git a/components/table/demo/bordered.ts b/components/table/demo/bordered.ts index 39d1b4cd773..a9450394e37 100644 --- a/components/table/demo/bordered.ts +++ b/components/table/demo/bordered.ts @@ -3,11 +3,7 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-table-bordered', template: ` - + Name @@ -17,9 +13,9 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} @@ -28,21 +24,21 @@ import { Component } from '@angular/core'; export class NzDemoTableBorderedComponent { dataSet = [ { - key : '1', - name : 'John Brown', - age : 32, + key: '1', + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - key : '2', - name : 'Jim Green', - age : 42, + key: '2', + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - key : '3', - name : 'Joe Black', - age : 32, + key: '3', + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' } ]; diff --git a/components/table/demo/colspan-rowspan.ts b/components/table/demo/colspan-rowspan.ts index 1ece6b9c4ab..5baa82da869 100644 --- a/components/table/demo/colspan-rowspan.ts +++ b/components/table/demo/colspan-rowspan.ts @@ -3,7 +3,7 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-table-colspan-rowspan', template: ` - + Name @@ -13,57 +13,58 @@ import { Component } from '@angular/core'; - + {{ data.name }} {{ data.age }} {{ data.tel }} - {{data.phone}} - {{data.address}} + {{ data.phone }} + {{ data.address }} - ` + + ` }) export class NzDemoTableColspanRowspanComponent { listOfData = [ { - key : '1', - name : 'John Brown', - age : 32, - tel : '0571-22098909', - phone : 18889898989, - address: 'New York No. 1 Lake Park', + key: '1', + name: 'John Brown', + age: 32, + tel: '0571-22098909', + phone: 18889898989, + address: 'New York No. 1 Lake Park' }, { - key : '2', - name : 'Jim Green', - tel : '0571-22098333', - phone : 18889898888, - age : 42, - address: 'London No. 1 Lake Park', + key: '2', + name: 'Jim Green', + tel: '0571-22098333', + phone: 18889898888, + age: 42, + address: 'London No. 1 Lake Park' }, { - key : '3', - name : 'Joe Black', - age : 32, - tel : '0575-22098909', - phone : 18900010002, - address: 'Sidney No. 1 Lake Park', + key: '3', + name: 'Joe Black', + age: 32, + tel: '0575-22098909', + phone: 18900010002, + address: 'Sidney No. 1 Lake Park' }, { - key : '4', - name : 'Jim Red', - age : 18, - tel : '0575-22098909', - phone : 18900010002, - address: 'London No. 2 Lake Park', + key: '4', + name: 'Jim Red', + age: 18, + tel: '0575-22098909', + phone: 18900010002, + address: 'London No. 2 Lake Park' }, { - key : '5', - name : 'Jake White', - age : 18, - tel : '0575-22098909', - phone : 18900010002, - address: 'Dublin No. 2 Lake Park', + key: '5', + name: 'Jake White', + age: 18, + tel: '0575-22098909', + phone: 18900010002, + address: 'Dublin No. 2 Lake Park' } ]; } diff --git a/components/table/demo/custom-filter-panel.ts b/components/table/demo/custom-filter-panel.ts index eadcb3b56aa..a222ac117ec 100644 --- a/components/table/demo/custom-filter-panel.ts +++ b/components/table/demo/custom-filter-panel.ts @@ -5,33 +5,41 @@ import { Component } from '@angular/core'; template: ` - - - Name - - - - - - Age - Address - + + + Name + + + + + + Age + Address + - - {{data.name}} - {{data.age}} - {{data.address}} - + + {{ data.name }} + {{ data.age }} + {{ data.address }} + - `, - styles : [ - ` + + `, + styles: [ + ` .search-box { padding: 8px; } @@ -56,34 +64,31 @@ export class NzDemoTableCustomFilterPanelComponent { searchValue = ''; sortName: string | null = null; sortValue: string | null = null; - listOfFilterAddress = [ - { text: 'London', value: 'London' }, - { text: 'Sidney', value: 'Sidney' } - ]; + listOfFilterAddress = [{ text: 'London', value: 'London' }, { text: 'Sidney', value: 'Sidney' }]; listOfSearchAddress: string[] = []; - listOfData = [ + listOfData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = [ { - name : 'John Brown', - age : 32, + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - name : 'Jim Green', - age : 42, + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - name : 'Joe Black', - age : 32, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' }, { - name : 'Jim Red', - age : 32, + name: 'Jim Red', + age: 32, address: 'London No. 2 Lake Park' } ]; - listOfDisplayData = [ ...this.listOfData ]; + listOfDisplayData = [...this.listOfData]; reset(): void { this.searchValue = ''; @@ -102,12 +107,22 @@ export class NzDemoTableCustomFilterPanelComponent { } search(): void { - const filterFunc = (item: { name: string, age: number, address: string }) => { - return (this.listOfSearchAddress.length ? this.listOfSearchAddress.some(address => item.address.indexOf(address) !== -1) : true) && - (item.name.indexOf(this.searchValue) !== -1); + const filterFunc = (item: { name: string; age: number; address: string }) => { + return ( + (this.listOfSearchAddress.length + ? this.listOfSearchAddress.some(address => item.address.indexOf(address) !== -1) + : true) && item.name.indexOf(this.searchValue) !== -1 + ); }; - const data = this.listOfData.filter((item: { name: string, age: number, address: string }) => filterFunc(item)); - // @ts-ignore - this.listOfDisplayData = data.sort((a, b) => (this.sortValue === 'ascend') ? (a[ this.sortName! ] > b[ this.sortName! ] ? 1 : -1) : (b[ this.sortName! ] > a[ this.sortName! ] ? 1 : -1)); + const data = this.listOfData.filter((item: { name: string; age: number; address: string }) => filterFunc(item)); + this.listOfDisplayData = data.sort((a, b) => + this.sortValue === 'ascend' + ? a[this.sortName!] > b[this.sortName!] + ? 1 + : -1 + : b[this.sortName!] > a[this.sortName!] + ? 1 + : -1 + ); } } diff --git a/components/table/demo/default-filter.ts b/components/table/demo/default-filter.ts index 389ffa5de2b..912f3c9b08e 100644 --- a/components/table/demo/default-filter.ts +++ b/components/table/demo/default-filter.ts @@ -6,52 +6,71 @@ import { Component } from '@angular/core'; - Name + + Name + Age - Address + + Address + - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - ` + + ` }) export class NzDemoTableDefaultFilterComponent { - listOfName = [ { text: 'Joe', value: 'Joe', byDefault: true }, { text: 'Jim', value: 'Jim' } ]; - listOfAddress = [ { text: 'London', value: 'London', byDefault: true }, { text: 'Sidney', value: 'Sidney' } ]; - listOfSearchName = [ 'Joe' ]; // You need to change it as well! + listOfName = [{ text: 'Joe', value: 'Joe', byDefault: true }, { text: 'Jim', value: 'Jim' }]; + listOfAddress = [{ text: 'London', value: 'London', byDefault: true }, { text: 'Sidney', value: 'Sidney' }]; + listOfSearchName = ['Joe']; // You need to change it as well! sortName: string | null = null; sortValue: string | null = null; searchAddress = 'London'; - listOfData = [ + listOfData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = [ { - name : 'John Brown', - age : 32, + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - name : 'Jim Green', - age : 42, + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - name : 'Joe Black', - age : 32, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' }, { - name : 'Jim Red', - age : 32, + name: 'Jim Red', + age: 32, address: 'London No. 2 Lake Park' } ]; - listOfDisplayData: any[] = []; // You need to change it as well! + // You need to change it as well! + listOfDisplayData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = []; - sort(sort: { key: string, value: string }): void { + sort(sort: { key: string; value: string }): void { this.sortName = sort.key; this.sortValue = sort.value; this.search(); @@ -66,12 +85,21 @@ export class NzDemoTableDefaultFilterComponent { search(): void { /** filter data **/ - const filterFunc = (item: { name: string, age: number, address: string }) => (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) && (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); + const filterFunc = (item: { name: string; age: number; address: string }) => + (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) && + (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); const data = this.listOfData.filter(item => filterFunc(item)); /** sort data **/ if (this.sortName && this.sortValue) { - // @ts-ignore - this.listOfDisplayData = data.sort((a, b) => (this.sortValue === 'ascend') ? (a[ this.sortName! ] > b[ this.sortName! ] ? 1 : -1) : (b[ this.sortName! ] > a[ this.sortName! ] ? 1 : -1)); + this.listOfDisplayData = data.sort((a, b) => + this.sortValue === 'ascend' + ? a[this.sortName!] > b[this.sortName!] + ? 1 + : -1 + : b[this.sortName!] > a[this.sortName!] + ? 1 + : -1 + ); } else { this.listOfDisplayData = data; } diff --git a/components/table/demo/drag-sorting.ts b/components/table/demo/drag-sorting.ts index 1daac660154..bf8e59b59b4 100644 --- a/components/table/demo/drag-sorting.ts +++ b/components/table/demo/drag-sorting.ts @@ -14,14 +14,14 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} `, - styles : [ + styles: [ ` ::ng-deep .cdk-drag-preview { display: table; @@ -30,28 +30,27 @@ import { Component } from '@angular/core'; ::ng-deep .cdk-drag-placeholder { opacity: 0; } - ` ] }) export class NzDemoTableDragSortingComponent { listOfData = [ { - key : '1', - name : 'John Brown', - age : 32, + key: '1', + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - key : '2', - name : 'Jim Green', - age : 42, + key: '2', + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - key : '3', - name : 'Joe Black', - age : 32, + key: '3', + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' } ]; diff --git a/components/table/demo/dynamic-settings.ts b/components/table/demo/dynamic-settings.ts index bcefcf1a3d2..0a9c59cd4fd 100644 --- a/components/table/demo/dynamic-settings.ts +++ b/components/table/demo/dynamic-settings.ts @@ -47,7 +47,9 @@ import { Component, OnInit } from '@angular/core'; - + @@ -75,7 +77,8 @@ import { Component, OnInit } from '@angular/core'; - + (nzCurrentPageDataChange)="currentPageDataChange($event)" + > - + Name Age Address @@ -104,24 +115,25 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - Action 一 {{data.name}} + Action 一 {{ data.name }} Delete - + - {{data.description}} + {{ data.description }}
    - `, - styles : [ - ` + + `, + styles: [ + ` .components-table-demo-control-bar { margin-bottom: 12px; } @@ -153,7 +165,16 @@ export class NzDemoTableDynamicSettingsComponent implements OnInit { noResult = false; position = 'bottom'; - currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; expand: boolean; description: string; }>): void { + currentPageDataChange( + $event: Array<{ + name: string; + age: number; + address: string; + checked: boolean; + expand: boolean; + description: string; + }> + ): void { this.displayData = $event; this.refreshStatus(); } @@ -163,7 +184,7 @@ export class NzDemoTableDynamicSettingsComponent implements OnInit { const allChecked = validData.length > 0 && validData.every(value => value.checked === true); const allUnChecked = validData.every(value => !value.checked); this.allChecked = allChecked; - this.indeterminate = (!allChecked) && (!allUnChecked); + this.indeterminate = !allChecked && !allUnChecked; } checkAll(value: boolean): void { @@ -178,12 +199,12 @@ export class NzDemoTableDynamicSettingsComponent implements OnInit { ngOnInit(): void { for (let i = 1; i <= 100; i++) { this.listOfData.push({ - name : 'John Brown', - age : `${i}2`, - address : `New York No. ${i} Lake Park`, + name: 'John Brown', + age: `${i}2`, + address: `New York No. ${i} Lake Park`, description: `My name is John Brown, I am ${i}2 years old, living in New York No. ${i} Lake Park.`, - checked : false, - expand : false + checked: false, + expand: false }); } } diff --git a/components/table/demo/edit-cell.ts b/components/table/demo/edit-cell.ts index 1941d122abd..8185ee5cd45 100644 --- a/components/table/demo/edit-cell.ts +++ b/components/table/demo/edit-cell.ts @@ -18,16 +18,16 @@ import { NzInputDirective } from 'ng-zorro-antd';
    -
    - {{data.name}} +
    + {{ data.name }}
    - + - {{data.age}} - {{data.address}} + {{ data.age }} + {{ data.address }} Delete @@ -35,8 +35,8 @@ import { NzInputDirective } from 'ng-zorro-antd'; `, - styles : [ - ` + styles: [ + ` button { margin-bottom: 16px; } @@ -64,7 +64,7 @@ export class NzDemoTableEditCellComponent implements OnInit { listOfData: any[] = []; @ViewChild(NzInputDirective, { read: ElementRef }) inputElement: ElementRef; - @HostListener('window:click', [ '$event' ]) + @HostListener('window:click', ['$event']) handleClick(e: MouseEvent): void { if (this.editId && this.inputElement && this.inputElement.nativeElement !== e.target) { this.editId = null; @@ -72,12 +72,15 @@ export class NzDemoTableEditCellComponent implements OnInit { } addRow(): void { - this.listOfData = [ ...this.listOfData, { - id : `${this.i}`, - name : `Edward King ${this.i}`, - age : '32', - address: `London, Park Lane no. ${this.i}` - } ]; + this.listOfData = [ + ...this.listOfData, + { + id: `${this.i}`, + name: `Edward King ${this.i}`, + age: '32', + address: `London, Park Lane no. ${this.i}` + } + ]; this.i++; } diff --git a/components/table/demo/edit-row.ts b/components/table/demo/edit-row.ts index dced996214b..62639030963 100644 --- a/components/table/demo/edit-row.ts +++ b/components/table/demo/edit-row.ts @@ -16,26 +16,26 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} + {{ data.name }} - + - {{data.age}} + {{ data.age }} - + - {{data.address}} + {{ data.address }} - + @@ -53,8 +53,8 @@ import { Component, OnInit } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` .editable-row-operations a { margin-right: 8px; } @@ -62,30 +62,30 @@ import { Component, OnInit } from '@angular/core'; ] }) export class NzDemoTableEditRowComponent implements OnInit { - editCache: { [ key: string ]: any } = {}; + editCache: { [key: string]: any } = {}; listOfData: any[] = []; startEdit(id: string): void { - this.editCache[ id ].edit = true; + this.editCache[id].edit = true; } cancelEdit(id: string): void { const index = this.listOfData.findIndex(item => item.id === id); - this.editCache[ id ] = { - data: { ...this.listOfData[ index ] }, + this.editCache[id] = { + data: { ...this.listOfData[index] }, edit: false }; } saveEdit(id: string): void { const index = this.listOfData.findIndex(item => item.id === id); - Object.assign(this.listOfData[ index ], this.editCache[ id ].data); - this.editCache[ id ].edit = false; + Object.assign(this.listOfData[index], this.editCache[id].data); + this.editCache[id].edit = false; } updateEditCache(): void { this.listOfData.forEach(item => { - this.editCache[ item.id ] = { + this.editCache[item.id] = { edit: false, data: { ...item } }; @@ -95,9 +95,9 @@ export class NzDemoTableEditRowComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfData.push({ - id : `${i}`, - name : `Edrward ${i}`, - age : 32, + id: `${i}`, + name: `Edrward ${i}`, + age: 32, address: `London Park no. ${i}` }); } diff --git a/components/table/demo/expand-children.ts b/components/table/demo/expand-children.ts index 4d461d3211a..c4029a69d53 100644 --- a/components/table/demo/expand-children.ts +++ b/components/table/demo/expand-children.ts @@ -15,79 +15,83 @@ export interface TreeNodeInterface { template: ` - - Name - Age - Address - + + Name + Age + Address + - - - - - {{item.name}} - - {{item.age}} - {{item.address}} - + + + + + {{ item.name }} + + {{ item.age }} + {{ item.address }} + + - - ` + + ` }) export class NzDemoTableExpandChildrenComponent implements OnInit { listOfMapData = [ { - key : 1, - name : 'John Brown sr.', - age : 60, - address : 'New York No. 1 Lake Park', + key: 1, + name: 'John Brown sr.', + age: 60, + address: 'New York No. 1 Lake Park', children: [ { - key : 11, - name : 'John Brown', - age : 42, + key: 11, + name: 'John Brown', + age: 42, address: 'New York No. 2 Lake Park' }, { - key : 12, - name : 'John Brown jr.', - age : 30, - address : 'New York No. 3 Lake Park', - children: [ { - key : 121, - name : 'Jimmy Brown', - age : 16, - address: 'New York No. 3 Lake Park' - } ] + key: 12, + name: 'John Brown jr.', + age: 30, + address: 'New York No. 3 Lake Park', + children: [ + { + key: 121, + name: 'Jimmy Brown', + age: 16, + address: 'New York No. 3 Lake Park' + } + ] }, { - key : 13, - name : 'Jim Green sr.', - age : 72, - address : 'London No. 1 Lake Park', + key: 13, + name: 'Jim Green sr.', + age: 72, + address: 'London No. 1 Lake Park', children: [ { - key : 131, - name : 'Jim Green', - age : 42, - address : 'London No. 2 Lake Park', + key: 131, + name: 'Jim Green', + age: 42, + address: 'London No. 2 Lake Park', children: [ { - key : 1311, - name : 'Jim Green jr.', - age : 25, + key: 1311, + name: 'Jim Green jr.', + age: 25, address: 'London No. 3 Lake Park' }, { - key : 1312, - name : 'Jimmy Green sr.', - age : 18, + key: 1312, + name: 'Jimmy Green sr.', + age: 18, address: 'London No. 4 Lake Park' } ] @@ -97,13 +101,13 @@ export class NzDemoTableExpandChildrenComponent implements OnInit { ] }, { - key : 2, - name : 'Joe Black', - age : 32, + key: 2, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' } ]; - mapOfExpandedData: { [ key: string ]: TreeNodeInterface[] } = {}; + mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {}; collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void { if ($event === false) { @@ -130,7 +134,7 @@ export class NzDemoTableExpandChildrenComponent implements OnInit { this.visitNode(node, hashMap, array); if (node.children) { for (let i = node.children.length - 1; i >= 0; i--) { - stack.push({ ...node.children[ i ], level: node.level + 1, expand: false, parent: node }); + stack.push({ ...node.children[i], level: node.level + 1, expand: false, parent: node }); } } } @@ -138,16 +142,16 @@ export class NzDemoTableExpandChildrenComponent implements OnInit { return array; } - visitNode(node: TreeNodeInterface, hashMap: { [ key: string ]: any }, array: TreeNodeInterface[]): void { - if (!hashMap[ node.key ]) { - hashMap[ node.key ] = true; + visitNode(node: TreeNodeInterface, hashMap: { [key: string]: any }, array: TreeNodeInterface[]): void { + if (!hashMap[node.key]) { + hashMap[node.key] = true; array.push(node); } } ngOnInit(): void { this.listOfMapData.forEach(item => { - this.mapOfExpandedData[ item.key ] = this.convertTreeToList(item); + this.mapOfExpandedData[item.key] = this.convertTreeToList(item); }); } } diff --git a/components/table/demo/expand.ts b/components/table/demo/expand.ts index 8be4f8a1489..cae2e791d9d 100644 --- a/components/table/demo/expand.ts +++ b/components/table/demo/expand.ts @@ -16,44 +16,45 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - {{data.description}} + {{ data.description }} - `, - styles : [] + + `, + styles: [] }) export class NzDemoTableExpandComponent { - mapOfExpandData: { [ key: string ]: boolean } = {}; + mapOfExpandData: { [key: string]: boolean } = {}; listOfData = [ { - id : 1, - name : 'John Brown', - age : 32, - expand : false, - address : 'New York No. 1 Lake Park', + id: 1, + name: 'John Brown', + age: 32, + expand: false, + address: 'New York No. 1 Lake Park', description: 'My name is John Brown, I am 32 years old, living in New York No. 1 Lake Park.' }, { - id : 2, - name : 'Jim Green', - age : 42, - expand : false, - address : 'London No. 1 Lake Park', + id: 2, + name: 'Jim Green', + age: 42, + expand: false, + address: 'London No. 1 Lake Park', description: 'My name is Jim Green, I am 42 years old, living in London No. 1 Lake Park.' }, { - id : 3, - name : 'Joe Black', - age : 32, - expand : false, - address : 'Sidney No. 1 Lake Park', + id: 3, + name: 'Joe Black', + age: 32, + expand: false, + address: 'Sidney No. 1 Lake Park', description: 'My name is Joe Black, I am 32 years old, living in Sidney No. 1 Lake Park.' } ]; diff --git a/components/table/demo/fixed-columns-header.ts b/components/table/demo/fixed-columns-header.ts index 8e44e6cec8e..6c0fdb37608 100644 --- a/components/table/demo/fixed-columns-header.ts +++ b/components/table/demo/fixed-columns-header.ts @@ -3,7 +3,7 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-table-fixed-columns-header', template: ` - + Full Name @@ -21,22 +21,23 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} action - ` + + ` }) export class NzDemoTableFixedColumnsHeaderComponent implements OnInit { listOfData: any[] = []; @@ -44,8 +45,8 @@ export class NzDemoTableFixedColumnsHeaderComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfData.push({ - name : `Edward King ${i}`, - age : 32, + name: `Edward King ${i}`, + age: 32, address: `London` }); } diff --git a/components/table/demo/fixed-columns.ts b/components/table/demo/fixed-columns.ts index 24d8d60c6cb..12004212fbd 100644 --- a/components/table/demo/fixed-columns.ts +++ b/components/table/demo/fixed-columns.ts @@ -3,7 +3,7 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-table-fixed-columns', template: ` - + Full Name @@ -21,35 +21,36 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} action - ` + + ` }) export class NzDemoTableFixedColumnsComponent { listOfData = [ { - key : '1', - name : 'John Brown', - age : 32, + key: '1', + name: 'John Brown', + age: 32, address: 'New York' }, { - key : '2', - name : 'Jim Green', - age : 40, + key: '2', + name: 'Jim Green', + age: 40, address: 'London' } ]; diff --git a/components/table/demo/fixed-header.ts b/components/table/demo/fixed-header.ts index 90085e11def..a4523c0f6d0 100644 --- a/components/table/demo/fixed-header.ts +++ b/components/table/demo/fixed-header.ts @@ -13,12 +13,13 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - ` + + ` }) export class NzDemoTableFixedHeaderComponent implements OnInit { listOfData: any[] = []; @@ -26,10 +27,10 @@ export class NzDemoTableFixedHeaderComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfData.push({ - name : `Edward King ${i}`, - age : 32, + name: `Edward King ${i}`, + age: 32, address: `London, Park Lane no. ${i}` }); } } -} \ No newline at end of file +} diff --git a/components/table/demo/grouping-columns.ts b/components/table/demo/grouping-columns.ts index 32c67668832..093cef3b729 100644 --- a/components/table/demo/grouping-columns.ts +++ b/components/table/demo/grouping-columns.ts @@ -3,7 +3,14 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-table-grouping-columns', template: ` - + Name @@ -28,28 +35,26 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.street}} - {{data.building}} - {{data.number}} - {{data.companyAddress}} - {{data.companyName}} - {{data.gender}} + {{ data.name }} + {{ data.age }} + {{ data.street }} + {{ data.building }} + {{ data.number }} + {{ data.companyAddress }} + {{ data.companyName }} + {{ data.gender }} - ` + + ` }) export class NzDemoTableGroupingColumnsComponent implements OnInit { - widthConfig = [ '100px', '200px', '200px', '100px', '100px', '200px', '200px', '100px' ]; + widthConfig = ['100px', '200px', '200px', '100px', '100px', '200px', '200px', '100px']; scrollConfig = { x: '1200px', y: '240px' }; listOfDisplayData: any[] = []; listOfData: any[] = []; sortValue: string | null = null; - filterName = [ - { text: 'Joe', value: 'Joe' }, - { text: 'John', value: 'John' } - ]; + filterName = [{ text: 'Joe', value: 'Joe' }, { text: 'John', value: 'John' }]; searchName: string[] = []; search(searchName: string[]): void { @@ -58,22 +63,24 @@ export class NzDemoTableGroupingColumnsComponent implements OnInit { return this.searchName.length ? this.searchName.some(name => item.name.indexOf(name) !== -1) : true; }; const listOfData = this.listOfData.filter(item => filterFunc(item)); - this.listOfDisplayData = listOfData.sort((a, b) => (this.sortValue === 'ascend') ? (a.age > b.age ? 1 : -1) : (b.age > a.age ? 1 : -1)); + this.listOfDisplayData = listOfData.sort((a, b) => + this.sortValue === 'ascend' ? (a.age > b.age ? 1 : -1) : b.age > a.age ? 1 : -1 + ); } ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfData.push({ - name : 'John Brown', - age : i + 1, - street : 'Lake Park', - building : 'C', - number : 2035, + name: 'John Brown', + age: i + 1, + street: 'Lake Park', + building: 'C', + number: 2035, companyAddress: 'Lake Street 42', - companyName : 'SoftLake Co', - gender : 'M' + companyName: 'SoftLake Co', + gender: 'M' }); } - this.listOfDisplayData = [ ...this.listOfData ]; + this.listOfDisplayData = [...this.listOfData]; } } diff --git a/components/table/demo/head.ts b/components/table/demo/head.ts index 3bee844fd60..9de0850ae27 100644 --- a/components/table/demo/head.ts +++ b/components/table/demo/head.ts @@ -6,52 +6,72 @@ import { Component } from '@angular/core'; - Name + + Name + Age - Address + + Address + - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - ` + + ` }) export class NzDemoTableHeadComponent { sortName: string | null = null; sortValue: string | null = null; searchAddress: string; - listOfName = [ { text: 'Joe', value: 'Joe' }, { text: 'Jim', value: 'Jim' } ]; - listOfAddress = [ { text: 'London', value: 'London' }, { text: 'Sidney', value: 'Sidney' } ]; + listOfName = [{ text: 'Joe', value: 'Joe' }, { text: 'Jim', value: 'Jim' }]; + listOfAddress = [{ text: 'London', value: 'London' }, { text: 'Sidney', value: 'Sidney' }]; listOfSearchName: string[] = []; - listOfData = [ + listOfData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = [ { - name : 'John Brown', - age : 32, + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - name : 'Jim Green', - age : 42, + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - name : 'Joe Black', - age : 32, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' }, { - name : 'Jim Red', - age : 32, + name: 'Jim Red', + age: 32, address: 'London No. 2 Lake Park' } ]; - listOfDisplayData: any[] = [ ...this.listOfData ]; + listOfDisplayData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = [ + ...this.listOfData + ]; - sort(sort: { key: string, value: string }): void { + sort(sort: { key: string; value: string }): void { this.sortName = sort.key; this.sortValue = sort.value; this.search(); @@ -65,12 +85,21 @@ export class NzDemoTableHeadComponent { search(): void { /** filter data **/ - const filterFunc = (item: { name: string, age: number, address: string }) => (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) && (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); + const filterFunc = (item: { name: string; age: number; address: string }) => + (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) && + (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); const data = this.listOfData.filter(item => filterFunc(item)); /** sort data **/ if (this.sortName && this.sortValue) { - // @ts-ignore - this.listOfDisplayData = data.sort((a, b) => (this.sortValue === 'ascend') ? (a[ this.sortName! ] > b[ this.sortName! ] ? 1 : -1) : (b[ this.sortName! ] > a[ this.sortName! ] ? 1 : -1)); + this.listOfDisplayData = data.sort((a, b) => + this.sortValue === 'ascend' + ? a[this.sortName!] > b[this.sortName!] + ? 1 + : -1 + : b[this.sortName!] > a[this.sortName!] + ? 1 + : -1 + ); } else { this.listOfDisplayData = data; } diff --git a/components/table/demo/nested-table.ts b/components/table/demo/nested-table.ts index 239f0098ff5..de667b5d124 100644 --- a/components/table/demo/nested-table.ts +++ b/components/table/demo/nested-table.ts @@ -20,12 +20,12 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.platform}} - {{data.version}} - {{data.upgradeNum}} - {{data.creator}} - {{data.createdAt}} + {{ data.name }} + {{ data.platform }} + {{ data.version }} + {{ data.upgradeNum }} + {{ data.creator }} + {{ data.createdAt }} Publish @@ -34,29 +34,27 @@ import { Component, OnInit } from '@angular/core'; - - - Date - Name - Status - Upgrade Status - Action - - - - - {{data.date}} - {{data.name}} - - - - {{data.upgradeNum}} - + + + Date + Name + Status + Upgrade Status + Action + + + + + {{ data.date }} + {{ data.name }} + + + + {{ data.upgradeNum }} + - - Pause - + Pause
    • Action 1 @@ -71,15 +69,15 @@ import { Component, OnInit } from '@angular/core'; More - - + + + + + + + - - - - - ` }) export class NzDemoTableNestedTableComponent implements OnInit { @@ -89,21 +87,21 @@ export class NzDemoTableNestedTableComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 3; ++i) { this.listOfParentData.push({ - key : i, - name : 'Screem', - platform : 'iOS', - version : '10.3.4.5654', + key: i, + name: 'Screem', + platform: 'iOS', + version: '10.3.4.5654', upgradeNum: 500, - creator : 'Jack', - createdAt : '2014-12-24 23:12:00', - expand : false + creator: 'Jack', + createdAt: '2014-12-24 23:12:00', + expand: false }); } for (let i = 0; i < 3; ++i) { this.listOfChildrenData.push({ - key : i, - date : '2014-12-24 23:12:00', - name : 'This is production name', + key: i, + date: '2014-12-24 23:12:00', + name: 'This is production name', upgradeNum: 'Upgraded: 56' }); } diff --git a/components/table/demo/reset-filter.ts b/components/table/demo/reset-filter.ts index d3416f8e6fc..474b5590afc 100644 --- a/components/table/demo/reset-filter.ts +++ b/components/table/demo/reset-filter.ts @@ -5,35 +5,54 @@ interface Data { age: number; address: string; - [ key: string ]: any; + [key: string]: any; } @Component({ selector: 'nz-demo-table-reset-filter', template: `
      - +
      - Name - Age - Address + + Name + + Age + + Address + - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - `, - styles : [ - ` + + `, + styles: [ + ` .table-operations { margin-bottom: 16px; } @@ -47,40 +66,34 @@ interface Data { export class NzDemoTableResetFilterComponent { listOfSearchName: string[] = []; listOfSearchAddress: string[] = []; - listOfFilterName = [ - { text: 'Joe', value: 'Joe' }, - { text: 'Jim', value: 'Jim' } - ]; - listOfFilterAddress = [ - { text: 'London', value: 'London' }, - { text: 'Sidney', value: 'Sidney' } - ]; + listOfFilterName = [{ text: 'Joe', value: 'Joe' }, { text: 'Jim', value: 'Jim' }]; + listOfFilterAddress = [{ text: 'London', value: 'London' }, { text: 'Sidney', value: 'Sidney' }]; listOfData: Data[] = [ { - name : 'John Brown', - age : 32, + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - name : 'Jim Green', - age : 42, + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - name : 'Joe Black', - age : 32, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' }, { - name : 'Jim Red', - age : 32, + name: 'Jim Red', + age: 32, address: 'London No. 2 Lake Park' } ]; - listOfDisplayData = [ ...this.listOfData ]; - mapOfSort: { [ key: string ]: any } = { - name : null, - age : null, + listOfDisplayData = [...this.listOfData]; + mapOfSort: { [key: string]: any } = { + name: null, + age: null, address: null }; sortName: string | null = null; @@ -90,7 +103,7 @@ export class NzDemoTableResetFilterComponent { this.sortName = sortName; this.sortValue = value; for (const key in this.mapOfSort) { - this.mapOfSort[ key ] = (key === sortName ? value : null); + this.mapOfSort[key] = key === sortName ? value : null; } this.search(this.listOfSearchName, this.listOfSearchAddress); } @@ -98,12 +111,21 @@ export class NzDemoTableResetFilterComponent { search(listOfSearchName: string[], listOfSearchAddress: string[]): void { this.listOfSearchName = listOfSearchName; this.listOfSearchAddress = listOfSearchAddress; - const filterFunc = (item: Data) => (this.listOfSearchAddress.length ? this.listOfSearchAddress.some(address => item.address.indexOf(address) !== -1) : true) && (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); + const filterFunc = (item: Data) => + (this.listOfSearchAddress.length + ? this.listOfSearchAddress.some(address => item.address.indexOf(address) !== -1) + : true) && + (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); const listOfData = this.listOfData.filter((item: Data) => filterFunc(item)); if (this.sortName && this.sortValue) { - this.listOfDisplayData = listOfData.sort((a, b) => (this.sortValue === 'ascend') - ? (a[ this.sortName! ] > b[ this.sortName! ] ? 1 : -1) - : (b[ this.sortName! ] > a[ this.sortName! ] ? 1 : -1) + this.listOfDisplayData = listOfData.sort((a, b) => + this.sortValue === 'ascend' + ? a[this.sortName!] > b[this.sortName!] + ? 1 + : -1 + : b[this.sortName!] > a[this.sortName!] + ? 1 + : -1 ); } else { this.listOfDisplayData = listOfData; @@ -111,14 +133,8 @@ export class NzDemoTableResetFilterComponent { } resetFilters(): void { - this.listOfFilterName = [ - { text: 'Joe', value: 'Joe' }, - { text: 'Jim', value: 'Jim' } - ]; - this.listOfFilterAddress = [ - { text: 'London', value: 'London' }, - { text: 'Sidney', value: 'Sidney' } - ]; + this.listOfFilterName = [{ text: 'Joe', value: 'Joe' }, { text: 'Jim', value: 'Jim' }]; + this.listOfFilterAddress = [{ text: 'London', value: 'London' }, { text: 'Sidney', value: 'Sidney' }]; this.listOfSearchName = []; this.listOfSearchAddress = []; this.search(this.listOfSearchName, this.listOfSearchAddress); @@ -128,8 +144,8 @@ export class NzDemoTableResetFilterComponent { this.sortName = null; this.sortValue = null; this.mapOfSort = { - name : null, - age : null, + name: null, + age: null, address: null }; this.resetFilters(); diff --git a/components/table/demo/row-selection-and-operation.ts b/components/table/demo/row-selection-and-operation.ts index c2ab899b473..381eb6a3b0d 100644 --- a/components/table/demo/row-selection-and-operation.ts +++ b/components/table/demo/row-selection-and-operation.ts @@ -12,17 +12,32 @@ export interface Data { selector: 'nz-demo-table-row-selection-and-operation', template: `
      - - Selected {{numberOfChecked}} items + + Selected {{ numberOfChecked }} items
      - + (nzCurrentPageDataChange)="currentPageDataChange($event)" + > - + Name Age Address @@ -30,15 +45,21 @@ export interface Data { - - {{data.name}} - {{data.age}} - {{data.address}} + + {{ data.name }} + {{ data.age }} + {{ data.address }} - `, - styles : [ - ` + + `, + styles: [ + ` .operate { margin-bottom: 16px; } @@ -55,7 +76,7 @@ export class NzDemoTableRowSelectionAndOperationComponent implements OnInit { isIndeterminate = false; listOfDisplayData: Data[] = []; listOfAllData: Data[] = []; - mapOfCheckedId: { [ key: string ]: boolean } = {}; + mapOfCheckedId: { [key: string]: boolean } = {}; numberOfChecked = 0; currentPageDataChange($event: Data[]): void { @@ -64,20 +85,24 @@ export class NzDemoTableRowSelectionAndOperationComponent implements OnInit { } refreshStatus(): void { - this.isAllDisplayDataChecked = this.listOfDisplayData.filter(item => !item.disabled).every(item => this.mapOfCheckedId[ item.id ]); - this.isIndeterminate = this.listOfDisplayData.filter(item => !item.disabled).some(item => this.mapOfCheckedId[ item.id ]) && !this.isAllDisplayDataChecked; - this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[ item.id ]).length; + this.isAllDisplayDataChecked = this.listOfDisplayData + .filter(item => !item.disabled) + .every(item => this.mapOfCheckedId[item.id]); + this.isIndeterminate = + this.listOfDisplayData.filter(item => !item.disabled).some(item => this.mapOfCheckedId[item.id]) && + !this.isAllDisplayDataChecked; + this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[item.id]).length; } checkAll(value: boolean): void { - this.listOfDisplayData.filter(item => !item.disabled).forEach(item => this.mapOfCheckedId[ item.id ] = value); + this.listOfDisplayData.filter(item => !item.disabled).forEach(item => (this.mapOfCheckedId[item.id] = value)); this.refreshStatus(); } operateData(): void { this.isOperating = true; setTimeout(() => { - this.listOfAllData.forEach(item => this.mapOfCheckedId[ item.id ] = false); + this.listOfAllData.forEach(item => (this.mapOfCheckedId[item.id] = false)); this.refreshStatus(); this.isOperating = false; }, 1000); @@ -86,10 +111,10 @@ export class NzDemoTableRowSelectionAndOperationComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfAllData.push({ - id : i, - name : `Edward King ${i}`, - age : 32, - address : `London, Park Lane no. ${i}`, + id: i, + name: `Edward King ${i}`, + age: 32, + address: `London, Park Lane no. ${i}`, disabled: i % 2 === 0 }); } diff --git a/components/table/demo/row-selection-custom.ts b/components/table/demo/row-selection-custom.ts index e13590c3e67..bb228af84b7 100644 --- a/components/table/demo/row-selection-custom.ts +++ b/components/table/demo/row-selection-custom.ts @@ -3,13 +3,22 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-table-row-selection-custom', template: ` - + (nzCurrentPageDataChange)="currentPageDataChange($event)" + > - + Name Age Address @@ -18,32 +27,33 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} - ` + + ` }) export class NzDemoTableRowSelectionCustomComponent implements OnInit { listOfSelection = [ { - text : 'Select All Row', + text: 'Select All Row', onSelect: () => { this.checkAll(true); } }, { - text : 'Select Odd Row', + text: 'Select Odd Row', onSelect: () => { - this.listOfDisplayData.forEach((data, index) => this.mapOfCheckedId[data.id] = index % 2 !== 0); + this.listOfDisplayData.forEach((data, index) => (this.mapOfCheckedId[data.id] = index % 2 !== 0)); this.refreshStatus(); } }, { - text : 'Select Even Row', + text: 'Select Even Row', onSelect: () => { - this.listOfDisplayData.forEach((data, index) => this.mapOfCheckedId[data.id] = index % 2 === 0); + this.listOfDisplayData.forEach((data, index) => (this.mapOfCheckedId[data.id] = index % 2 === 0)); this.refreshStatus(); } } @@ -52,30 +62,31 @@ export class NzDemoTableRowSelectionCustomComponent implements OnInit { isIndeterminate = false; listOfDisplayData: any[] = []; listOfAllData: any[] = []; - mapOfCheckedId: { [ key: string ]: boolean } = {}; + mapOfCheckedId: { [key: string]: boolean } = {}; - currentPageDataChange($event: Array<{ id: number, name: string; age: number; address: string}>): void { + currentPageDataChange($event: Array<{ id: number; name: string; age: number; address: string }>): void { this.listOfDisplayData = $event; this.refreshStatus(); } refreshStatus(): void { - this.isAllDisplayDataChecked = this.listOfDisplayData.every(item => this.mapOfCheckedId[ item.id ]); - this.isIndeterminate = this.listOfDisplayData.some(item => this.mapOfCheckedId[ item.id ]) && !this.isAllDisplayDataChecked; + this.isAllDisplayDataChecked = this.listOfDisplayData.every(item => this.mapOfCheckedId[item.id]); + this.isIndeterminate = + this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) && !this.isAllDisplayDataChecked; } checkAll(value: boolean): void { - this.listOfDisplayData.forEach(item => this.mapOfCheckedId[ item.id ] = value); + this.listOfDisplayData.forEach(item => (this.mapOfCheckedId[item.id] = value)); this.refreshStatus(); } ngOnInit(): void { for (let i = 0; i < 100; i++) { this.listOfAllData.push({ - id : i, - name : `Edward King ${i}`, - age : 32, - address : `London, Park Lane no. ${i}` + id: i, + name: `Edward King ${i}`, + age: 32, + address: `London, Park Lane no. ${i}` }); } } diff --git a/components/table/demo/size.ts b/components/table/demo/size.ts index 88e0309c659..e383c2004e8 100644 --- a/components/table/demo/size.ts +++ b/components/table/demo/size.ts @@ -4,10 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-table-size', template: `

      Middle size table

      - + Name @@ -17,17 +14,14 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }}

      Small size table

      - + Name @@ -37,36 +31,40 @@ import { Component } from '@angular/core'; - {{data.name}} - {{data.age}} - {{data.address}} + {{ data.name }} + {{ data.age }} + {{ data.address }} `, - styles : [ - `h4 { margin-bottom: 16px; }` + styles: [ + ` + h4 { + margin-bottom: 16px; + } + ` ] }) export class NzDemoTableSizeComponent { data = [ { - key : '1', - name : 'John Brown', - age : 32, - address: 'New York No. 1 Lake Park', + key: '1', + name: 'John Brown', + age: 32, + address: 'New York No. 1 Lake Park' }, { - key : '2', - name : 'Jim Green', - age : 42, - address: 'London No. 1 Lake Park', + key: '2', + name: 'Jim Green', + age: 42, + address: 'London No. 1 Lake Park' }, { - key : '3', - name : 'Joe Black', - age : 32, - address: 'Sidney No. 1 Lake Park', + key: '3', + name: 'Joe Black', + age: 32, + address: 'Sidney No. 1 Lake Park' } ]; } diff --git a/components/table/demo/template.ts b/components/table/demo/template.ts index 84dc02a5f21..b2b3332b836 100644 --- a/components/table/demo/template.ts +++ b/components/table/demo/template.ts @@ -46,5 +46,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTableTemplateComponent { -} +export class NzDemoTableTemplateComponent {} diff --git a/components/table/demo/virtual.ts b/components/table/demo/virtual.ts index d57be974826..5162288b6bf 100644 --- a/components/table/demo/virtual.ts +++ b/components/table/demo/virtual.ts @@ -3,12 +3,14 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-table-virtual', template: ` - + [nzScroll]="{ x: '1200px', y: '240px' }" + > Full Name @@ -27,16 +29,16 @@ import { Component, OnInit } from '@angular/core'; - {{data.name}} {{index}} - {{data.age}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} + {{ data.name }} {{ index }} + {{ data.age }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} action @@ -52,8 +54,8 @@ export class NzDemoTableVirtualComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 20000; i++) { this.listOfData.push({ - name : `Edward King`, - age : 32, + name: `Edward King`, + age: 32, address: `London` }); } diff --git a/components/table/nz-table.component.ts b/components/table/nz-table.component.ts index 3cfb6e7eda0..0065567348d 100644 --- a/components/table/nz-table.component.ts +++ b/components/table/nz-table.component.ts @@ -4,7 +4,8 @@ import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, - Component, ContentChild, + Component, + ContentChild, ContentChildren, ElementRef, EventEmitter, @@ -32,18 +33,18 @@ import { NzTheadComponent } from './nz-thead.component'; import { NzVirtualScrollDirective } from './nz-virtual-scroll.directive'; @Component({ - selector : 'nz-table', + selector: 'nz-table', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-table.component.html', - host : { + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-table.component.html', + host: { '[class.ant-table-empty]': 'data.length === 0' }, - styles : [ - ` + styles: [ + ` nz-table { - display: block + display: block; } ` ] @@ -64,8 +65,8 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha @ViewChild(CdkVirtualScrollViewport, { read: ElementRef }) cdkVirtualScrollElement: ElementRef; @ContentChild(NzVirtualScrollDirective) nzVirtualScrollDirective: NzVirtualScrollDirective; @Input() nzSize: NzSizeMDSType = 'default'; - @Input() nzShowTotal: TemplateRef<{ $implicit: number, range: [ number, number ] }>; - @Input() nzPageSizeOptions = [ 10, 20, 30, 40, 50 ]; + @Input() nzShowTotal: TemplateRef<{ $implicit: number; range: [number, number] }>; + @Input() nzPageSizeOptions = [10, 20, 30, 40, 50]; @Input() @InputBoolean() nzVirtualScroll = false; @Input() @InputNumber() nzVirtualItemSize = 0; @Input() @InputNumber() nzVirtualMaxBufferPx = 200; @@ -81,7 +82,10 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha @Input() nzData = []; @Input() nzPaginationPosition: 'top' | 'bottom' | 'both' = 'bottom'; @Input() nzScroll: { x: string | null; y: string | null } = { x: null, y: null }; - @Input() @ViewChild('renderItemTemplate') nzItemRender: TemplateRef<{ $implicit: 'page' | 'prev' | 'next', page: number }>; + @Input() @ViewChild('renderItemTemplate') nzItemRender: TemplateRef<{ + $implicit: 'page' | 'prev' | 'next'; + page: number; + }>; @Input() @InputBoolean() nzFrontPagination = true; @Input() @InputBoolean() nzTemplateMode = false; @Input() @InputBoolean() nzBordered = false; @@ -143,11 +147,17 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha setScrollPositionClassName(): void { if (this.mixTableBodyNativeElement && this.nzScroll && this.nzScroll.x) { - if ((this.mixTableBodyNativeElement.scrollWidth === this.mixTableBodyNativeElement.clientWidth) && (this.mixTableBodyNativeElement.scrollWidth !== 0)) { + if ( + this.mixTableBodyNativeElement.scrollWidth === this.mixTableBodyNativeElement.clientWidth && + this.mixTableBodyNativeElement.scrollWidth !== 0 + ) { this.setScrollName(); } else if (this.mixTableBodyNativeElement.scrollLeft === 0) { this.setScrollName('left'); - } else if (this.mixTableBodyNativeElement.scrollWidth === (this.mixTableBodyNativeElement.scrollLeft + this.mixTableBodyNativeElement.clientWidth)) { + } else if ( + this.mixTableBodyNativeElement.scrollWidth === + this.mixTableBodyNativeElement.scrollLeft + this.mixTableBodyNativeElement.clientWidth + ) { this.setScrollName('right'); } else { this.setScrollName('middle'); @@ -157,7 +167,7 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha setScrollName(position?: string): void { const prefix = 'ant-table-scroll-position'; - const classList = [ 'left', 'right', 'middle' ]; + const classList = ['left', 'right', 'middle']; classList.forEach(name => { this.renderer.removeClass(this.tableMainElement.nativeElement, `${prefix}-${name}`); }); @@ -170,7 +180,7 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha const scrollbarWidth = this.nzMeasureScrollbarService.scrollBarWidth; if (scrollbarWidth) { this.headerBottomStyle = { - marginBottom : `-${scrollbarWidth}px`, + marginBottom: `-${scrollbarWidth}px`, paddingBottom: `0px` }; this.cdr.markForCheck(); @@ -193,11 +203,18 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha } else { data = this.nzData; } - this.data = [ ...data ]; + this.data = [...data]; this.nzCurrentPageDataChange.next(this.data); } - constructor(private renderer: Renderer2, private ngZone: NgZone, private cdr: ChangeDetectorRef, private nzMeasureScrollbarService: NzMeasureScrollbarService, private i18n: NzI18nService, elementRef: ElementRef) { + constructor( + private renderer: Renderer2, + private ngZone: NgZone, + private cdr: ChangeDetectorRef, + private nzMeasureScrollbarService: NzMeasureScrollbarService, + private i18n: NzI18nService, + elementRef: ElementRef + ) { renderer.addClass(elementRef.nativeElement, 'ant-table-wrapper'); } @@ -220,7 +237,6 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha if (changes.nzPageIndex || changes.nzPageSize || changes.nzFrontPagination || changes.nzData) { this.updateFrontPaginationDataIfNeeded(!!(changes.nzPageSize || changes.nzData)); } - } ngAfterViewInit(): void { @@ -229,24 +245,35 @@ export class NzTableComponent implements OnInit, AfterViewInit, OnDestroy, OnCha merge( this.tableHeaderNativeElement ? fromEvent(this.tableHeaderNativeElement, 'scroll') : EMPTY, this.mixTableBodyNativeElement ? fromEvent(this.mixTableBodyNativeElement, 'scroll') : EMPTY - ).pipe(takeUntil(this.destroy$)).subscribe((data: MouseEvent) => { - this.syncScrollTable(data); - }); - fromEvent(window, 'resize').pipe(startWith(true), takeUntil(this.destroy$)).subscribe(() => { - this.fitScrollBar(); - this.setScrollPositionClassName(); - }); + ) + .pipe(takeUntil(this.destroy$)) + .subscribe((data: MouseEvent) => { + this.syncScrollTable(data); + }); + fromEvent(window, 'resize') + .pipe( + startWith(true), + takeUntil(this.destroy$) + ) + .subscribe(() => { + this.fitScrollBar(); + this.setScrollPositionClassName(); + }); }); } ngAfterContentInit(): void { - this.listOfNzThComponent.changes.pipe( - startWith(true), - flatMap(() => merge(this.listOfNzThComponent.changes, ...this.listOfNzThComponent.map(th => th.nzWidthChange$))), - takeUntil(this.destroy$) - ).subscribe(() => { - this.cdr.markForCheck(); - }); + this.listOfNzThComponent.changes + .pipe( + startWith(true), + flatMap(() => + merge(this.listOfNzThComponent.changes, ...this.listOfNzThComponent.map(th => th.nzWidthChange$)) + ), + takeUntil(this.destroy$) + ) + .subscribe(() => { + this.cdr.markForCheck(); + }); } ngOnDestroy(): void { diff --git a/components/table/nz-table.module.ts b/components/table/nz-table.module.ts index 06e1e9fbd13..ef03709c979 100644 --- a/components/table/nz-table.module.ts +++ b/components/table/nz-table.module.ts @@ -22,9 +22,25 @@ import { NzTrDirective } from './nz-tr.directive'; import { NzVirtualScrollDirective } from './nz-virtual-scroll.directive'; @NgModule({ - declarations: [ NzTableComponent, NzThComponent, NzTdComponent, NzTheadComponent, NzTbodyDirective, NzTrDirective, NzVirtualScrollDirective ], - exports : [ NzTableComponent, NzThComponent, NzTdComponent, NzTheadComponent, NzTbodyDirective, NzTrDirective, NzVirtualScrollDirective ], - imports : [ + declarations: [ + NzTableComponent, + NzThComponent, + NzTdComponent, + NzTheadComponent, + NzTbodyDirective, + NzTrDirective, + NzVirtualScrollDirective + ], + exports: [ + NzTableComponent, + NzThComponent, + NzTdComponent, + NzTheadComponent, + NzTbodyDirective, + NzTrDirective, + NzVirtualScrollDirective + ], + imports: [ NzMenuModule, FormsModule, NzAddOnModule, @@ -40,5 +56,4 @@ import { NzVirtualScrollDirective } from './nz-virtual-scroll.directive'; ScrollingModule ] }) -export class NzTableModule { -} +export class NzTableModule {} diff --git a/components/table/nz-table.spec.ts b/components/table/nz-table.spec.ts index 9d520b88895..cb87bc59d49 100644 --- a/components/table/nz-table.spec.ts +++ b/components/table/nz-table.spec.ts @@ -11,8 +11,8 @@ describe('nz-table', () => { beforeEach(async(() => { injector = TestBed.configureTestingModule({ - imports : [ NzTableModule ], - declarations: [ NzTestTableBasicComponent, NzTestTableScrollComponent, NzTableSpecCrashComponent ] + imports: [NzTableModule], + declarations: [NzTestTableBasicComponent, NzTestTableScrollComponent, NzTableSpecCrashComponent] }); TestBed.compileComponents(); })); @@ -46,7 +46,7 @@ describe('nz-table', () => { fixture.detectChanges(); expect(testComponent.pageIndex).toBe(1); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); - table.nativeElement.querySelectorAll('.ant-pagination-item')[ 1 ].click(); + table.nativeElement.querySelectorAll('.ant-pagination-item')[1].click(); fixture.detectChanges(); expect(testComponent.pageIndex).toBe(2); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(1); @@ -99,7 +99,7 @@ describe('nz-table', () => { fixture.detectChanges(); expect(testComponent.pageSizeChange).toHaveBeenCalledTimes(0); expect(testComponent.pageIndexChange).toHaveBeenCalledTimes(0); - testComponent.dataSet = [ ...testComponent.dataSet, ...testComponent.dataSet ]; + testComponent.dataSet = [...testComponent.dataSet, ...testComponent.dataSet]; fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -181,10 +181,10 @@ describe('nz-table', () => { it('should width config', () => { fixture.detectChanges(); expect(table.nativeElement.querySelectorAll('col').length).toBe(4); - testComponent.widthConfig = [ '100px', '50px' ]; + testComponent.widthConfig = ['100px', '50px']; fixture.detectChanges(); - expect(table.nativeElement.querySelectorAll('col')[ 0 ].style.width).toBe('100px'); - expect(table.nativeElement.querySelectorAll('col')[ 1 ].style.width).toBe('50px'); + expect(table.nativeElement.querySelectorAll('col')[0].style.width).toBe('100px'); + expect(table.nativeElement.querySelectorAll('col')[1].style.width).toBe('50px'); }); it('should showQuickJumper & showSizeChanger work', () => { fixture.detectChanges(); @@ -199,7 +199,7 @@ describe('nz-table', () => { fixture.detectChanges(); expect(table.nativeElement.querySelector('.ant-pagination')).not.toBe(null); testComponent.hideOnSinglePage = true; - testComponent.dataSet = [ {} ]; + testComponent.dataSet = [{}]; fixture.detectChanges(); expect(table.nativeElement.querySelector('.ant-pagination')).toBe(null); }); @@ -320,7 +320,7 @@ describe('nz-table', () => { template: ` { [nzWidthConfig]="widthConfig" [nzShowPagination]="pagination" [nzFrontPagination]="pagination" - [nzFooter]="footer?'Here is Footer':null" + [nzFooter]="footer ? 'Here is Footer' : null" [nzNoResult]="noResult" - [nzTitle]="title?'Here is Title':null" - [nzSize]="size"> + [nzTitle]="title ? 'Here is Title' : null" + [nzSize]="size" + > - - Name - Age - Address - Action - - - - - {{data.name}} - {{data.age}} - {{data.address}} - - Action 一 {{data.name}} - Delete - + Name + Age + Address + Action - + + + + + {{ data.name }} + {{ data.age }} + {{ data.address }} + + Action 一 {{ data.name }} + Delete + + + ` @@ -369,7 +370,14 @@ export class NzTestTableBasicComponent implements OnInit { pageIndexChange = jasmine.createSpy('pageIndex callback'); pageSize = 10; pageSizeChange = jasmine.createSpy('pageSize callback'); - dataSet: Array<{ name?: string, age?: string, address?: string, description?: string, checked?: boolean, expand?: boolean }> = []; + dataSet: Array<{ + name?: string; + age?: string; + address?: string; + description?: string; + checked?: boolean; + expand?: boolean; + }> = []; noResult = ''; showSizeChanger = false; showQuickJumper = false; @@ -388,73 +396,70 @@ export class NzTestTableBasicComponent implements OnInit { ngOnInit(): void { for (let i = 1; i <= 20; i++) { this.dataSet.push({ - name : 'John Brown', - age : `${i}2`, - address : `New York No. ${i} Lake Park`, + name: 'John Brown', + age: `${i}2`, + address: `New York No. ${i} Lake Park`, description: `My name is John Brown, I am ${i}2 years old, living in New York No. ${i} Lake Park.`, - checked : false, - expand : false + checked: false, + expand: false }); } } } @Component({ - selector : 'nz-test-table-scroll', - template : ` + selector: 'nz-test-table-scroll', + template: `
      - + - - Full Name - Age - Column 1 - Column 2 - Column 3 - Column 4 - Column 5 - Column 6 - Column 7 - Column 8 - Action - + + Full Name + Age + Column 1 + Column 2 + Column 3 + Column 4 + Column 5 + Column 6 + Column 7 + Column 8 + Action + - - {{data.name}} - {{data.age}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - {{data.address}} - - action - - + + {{ data.name }} + {{ data.age }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + {{ data.address }} + + action + + -
      `, +
    + `, encapsulation: ViewEncapsulation.None, - styleUrls : [ - '../style/index.less', - '../spin/style/index.less', - './style/index.less' - ] + styleUrls: ['../style/index.less', '../spin/style/index.less', './style/index.less'] }) export class NzTestTableScrollComponent implements OnInit { @ViewChild(NzTableComponent) nzTableComponent: NzTableComponent; - dataSet: Array<{ name: string, age: number, address: string }> = []; + dataSet: Array<{ name: string; age: number; address: string }> = []; width = 300; ngOnInit(): void { for (let i = 0; i < 100; i++) { this.dataSet.push({ - name : `Edward King ${i}`, - age : 32, + name: `Edward King ${i}`, + age: 32, address: `London, Park Lane no. ${i}` }); } @@ -464,27 +469,32 @@ export class NzTestTableScrollComponent implements OnInit { /** https://github.com/NG-ZORRO/ng-zorro-antd/issues/3004 **/ @Component({ template: ` - + - - ID - NAME - - - - - {{item.id}} - {{item.name}} + ID + NAME - + + + + + {{ item.id }} + {{ item.name }} + + ` }) export class NzTableSpecCrashComponent { - data: Array<{ id: number, name: string }> = []; + data: Array<{ id: number; name: string }> = []; pageIndex = 1; pageSize = 10; pageIndexChange = jasmine.createSpy('pageSize callback'); @@ -492,10 +502,9 @@ export class NzTableSpecCrashComponent { constructor() { setTimeout(() => { this.data = new Array(100).fill(1).map((_, i) => ({ - id : i + 1, + id: i + 1, name: `name ${i + 1}` })); }, 1000); - } } diff --git a/components/table/nz-tbody.directive.ts b/components/table/nz-tbody.directive.ts index b9d4f096c72..f9e05088202 100644 --- a/components/table/nz-tbody.directive.ts +++ b/components/table/nz-tbody.directive.ts @@ -4,12 +4,10 @@ import { NzTableComponent } from './nz-table.component'; @Directive({ // tslint:disable-next-line:directive-selector selector: 'tbody', - host : { + host: { '[class.ant-table-tbody]': 'nzTableComponent' } }) - export class NzTbodyDirective { - constructor(@Host() @Optional() public nzTableComponent: NzTableComponent) { - } + constructor(@Host() @Optional() public nzTableComponent: NzTableComponent) {} } diff --git a/components/table/nz-tbody.spec.ts b/components/table/nz-tbody.spec.ts index 8b85a1a24fa..47d4486b788 100644 --- a/components/table/nz-tbody.spec.ts +++ b/components/table/nz-tbody.spec.ts @@ -8,9 +8,9 @@ import { NzTbodyDirective } from './nz-tbody.directive'; describe('nz-tbody', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTableModule ], - declarations: [ NzTbodyTestTableComponent, NzTbodyTestNzTableComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NzTableModule], + declarations: [NzTbodyTestTableComponent, NzTbodyTestNzTableComponent], + providers: [NzMeasureScrollbarService] }); TestBed.compileComponents(); })); @@ -51,17 +51,18 @@ describe('nz-tbody', () => { template: ` -
    ` + + ` }) -export class NzTbodyTestTableComponent { -} +export class NzTbodyTestTableComponent {} @Component({ selector: 'nz-tbody-test-nz-table', template: ` - ` +
    + ` }) export class NzTbodyTestNzTableComponent { expand = false; diff --git a/components/table/nz-td.component.ts b/components/table/nz-td.component.ts index 714d174e59e..cae8f23f3cf 100644 --- a/components/table/nz-td.component.ts +++ b/components/table/nz-td.component.ts @@ -16,15 +16,15 @@ import { InputBoolean } from '../core/util/convert'; @Component({ // tslint:disable-next-line:component-selector - selector : 'td:not(.nz-disable-td)', - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ NzUpdateHostClassService ], + selector: 'td:not(.nz-disable-td)', + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-td.component.html', - host : { - '[style.left]' : 'nzLeft', - '[style.right]' : 'nzRight', + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-td.component.html', + host: { + '[style.left]': 'nzLeft', + '[style.right]': 'nzRight', '[style.text-align]': 'nzAlign' } }) @@ -50,15 +50,14 @@ export class NzTdComponent implements OnChanges { setClassMap(): void { this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ `ant-table-row-expand-icon-cell` ]: this.nzShowExpand && !isNotNil(this.nzIndentSize), - [ `ant-table-selection-column` ] : this.nzShowCheckbox, - [ `ant-table-td-left-sticky` ] : isNotNil(this.nzLeft), - [ `ant-table-td-right-sticky` ] : isNotNil(this.nzRight) + [`ant-table-row-expand-icon-cell`]: this.nzShowExpand && !isNotNil(this.nzIndentSize), + [`ant-table-selection-column`]: this.nzShowCheckbox, + [`ant-table-td-left-sticky`]: isNotNil(this.nzLeft), + [`ant-table-td-right-sticky`]: isNotNil(this.nzRight) }); } - constructor(private elementRef: ElementRef, private nzUpdateHostClassService: NzUpdateHostClassService) { - } + constructor(private elementRef: ElementRef, private nzUpdateHostClassService: NzUpdateHostClassService) {} ngOnChanges(changes: SimpleChanges): void { if (changes.nzIndentSize || changes.nzShowExpand || changes.nzShowCheckbox || changes.nzRight || changes.nzLeft) { diff --git a/components/table/nz-td.spec.ts b/components/table/nz-td.spec.ts index 8cc256a5695..30bb599e3cc 100644 --- a/components/table/nz-td.spec.ts +++ b/components/table/nz-td.spec.ts @@ -9,8 +9,8 @@ import { NzTdComponent } from './nz-td.component'; describe('nz-td', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzCheckboxModule, FormsModule ], - declarations: [ NzTestTdComponent, NzTdComponent ] + imports: [NzCheckboxModule, FormsModule], + declarations: [NzTestTdComponent, NzTdComponent] }); TestBed.compileComponents(); })); @@ -38,13 +38,17 @@ describe('nz-td', () => { it('should checked work', fakeAsync(() => { testComponent.showCheckbox = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).not.toContain( + 'ant-checkbox-checked' + ); testComponent.checked = true; fixture.detectChanges(); flush(); fixture.detectChanges(); expect(testComponent.checked).toBe(true); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).toContain('ant-checkbox-checked'); + expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).toContain( + 'ant-checkbox-checked' + ); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); })); it('should disabled work', () => { @@ -53,12 +57,20 @@ describe('nz-td', () => { testComponent.disabled = true; fixture.detectChanges(); expect(testComponent.checked).toBe(false); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-checked')).toBe(false); + expect( + td.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-checked') + ).toBe(false); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); td.nativeElement.querySelector('.ant-checkbox-wrapper').click(); fixture.detectChanges(); expect(testComponent.checked).toBe(false); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-checked')).toBe(false); + expect( + td.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-checked') + ).toBe(false); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); }); it('should indeterminate work', () => { @@ -67,10 +79,18 @@ describe('nz-td', () => { fixture.detectChanges(); testComponent.indeterminate = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-indeterminate')).toBe(true); + expect( + td.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-indeterminate') + ).toBe(true); testComponent.checked = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-indeterminate')).toBe(true); + expect( + td.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-indeterminate') + ).toBe(true); }); it('should showExpand work', () => { fixture.detectChanges(); @@ -86,20 +106,28 @@ describe('nz-td', () => { it('should expand work', () => { testComponent.showExpand = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain('ant-table-row-collapsed'); + expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain( + 'ant-table-row-collapsed' + ); testComponent.expand = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain('ant-table-row-expanded'); + expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain( + 'ant-table-row-expanded' + ); expect(testComponent.expandChange).toHaveBeenCalledTimes(0); }); it('should click expand work', () => { testComponent.showExpand = true; fixture.detectChanges(); - expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain('ant-table-row-collapsed'); + expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain( + 'ant-table-row-collapsed' + ); td.nativeElement.querySelector('.ant-table-row-expand-icon').click(); fixture.detectChanges(); expect(testComponent.expand).toBe(true); - expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain('ant-table-row-expanded'); + expect(td.nativeElement.querySelector('.ant-table-row-expand-icon').classList).toContain( + 'ant-table-row-expanded' + ); expect(testComponent.expandChange).toHaveBeenCalledTimes(1); }); it('should click expand event stopPropagation', () => { @@ -149,7 +177,7 @@ describe('nz-td', () => { it('should be throw error when use specific class name', () => { expect(() => { TestBed.configureTestingModule({ - declarations: [ NzTestDisableTdComponent ] + declarations: [NzTestDisableTdComponent] }).createComponent(NzTestDisableTdComponent); }).toThrow(); }); @@ -170,7 +198,9 @@ describe('nz-td', () => { (nzExpandChange)="expandChange($event)" [nzIndentSize]="indentSize" [nzLeft]="left" - [nzRight]="right">` + [nzRight]="right" + > + ` }) export class NzTestTdComponent { showCheckbox = false; @@ -192,5 +222,4 @@ export class NzTestTdComponent { ` }) -export class NzTestDisableTdComponent { -} +export class NzTestDisableTdComponent {} diff --git a/components/table/nz-th.component.ts b/components/table/nz-th.component.ts index b99a659b730..cb3a77b3d82 100644 --- a/components/table/nz-th.component.ts +++ b/components/table/nz-th.component.ts @@ -4,7 +4,9 @@ import { Component, EventEmitter, Input, - OnChanges, OnDestroy, OnInit, + OnChanges, + OnDestroy, + OnInit, Output, SimpleChanges, ViewChild, @@ -30,24 +32,24 @@ export interface NzThItemInterface { @Component({ // tslint:disable-next-line:component-selector - selector : 'th:not(.nz-disable-th)', + selector: 'th:not(.nz-disable-th)', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-th.component.html', - host : { - '[class.ant-table-column-has-actions]' : 'nzShowFilter || nzShowSort || nzCustomFilter', - '[class.ant-table-column-has-filters]' : 'nzShowFilter || nzCustomFilter', - '[class.ant-table-column-has-sorters]' : 'nzShowSort', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-th.component.html', + host: { + '[class.ant-table-column-has-actions]': 'nzShowFilter || nzShowSort || nzCustomFilter', + '[class.ant-table-column-has-filters]': 'nzShowFilter || nzCustomFilter', + '[class.ant-table-column-has-sorters]': 'nzShowSort', '[class.ant-table-selection-column-custom]': 'nzShowRowSelection', - '[class.ant-table-selection-column]' : 'nzShowCheckbox', - '[class.ant-table-expand-icon-th]' : 'nzExpand', - '[class.ant-table-th-left-sticky]' : 'nzLeft', - '[class.ant-table-th-right-sticky]' : 'nzRight', - '[class.ant-table-column-sort]' : `nzSort === 'descend' || nzSort === 'ascend'`, - '[style.left]' : 'nzLeft', - '[style.right]' : 'nzRight', - '[style.text-align]' : 'nzAlign' + '[class.ant-table-selection-column]': 'nzShowCheckbox', + '[class.ant-table-expand-icon-th]': 'nzExpand', + '[class.ant-table-th-left-sticky]': 'nzLeft', + '[class.ant-table-th-right-sticky]': 'nzRight', + '[class.ant-table-column-sort]': `nzSort === 'descend' || nzSort === 'ascend'`, + '[style.left]': 'nzLeft', + '[style.right]': 'nzRight', + '[style.text-align]': 'nzAlign' } }) export class NzThComponent implements OnChanges, OnInit, OnDestroy { @@ -62,7 +64,7 @@ export class NzThComponent implements OnChanges, OnInit, OnDestroy { private hasDefaultFilter = false; @ViewChild(NzDropDownComponent) nzDropDownComponent: NzDropDownComponent; /* tslint:disable-next-line:no-any */ - @Input() nzSelections: Array<{ text: string, onSelect(...args: any[]): any; }> = []; + @Input() nzSelections: Array<{ text: string; onSelect(...args: any[]): any }> = []; @Input() nzChecked = false; @Input() nzDisabled = false; @Input() nzIndeterminate = false; @@ -72,7 +74,7 @@ export class NzThComponent implements OnChanges, OnInit, OnDestroy { @Input() nzLeft: string; @Input() nzRight: string; @Input() nzAlign: 'left' | 'right' | 'center'; - @Input() nzSort: 'ascend' | 'descend'| null = null; + @Input() nzSort: 'ascend' | 'descend' | null = null; @Input() nzFilters: NzThFilterType = []; @Input() @InputBoolean() nzExpand = false; @Input() @InputBoolean() nzShowCheckbox = false; @@ -82,7 +84,7 @@ export class NzThComponent implements OnChanges, OnInit, OnDestroy { @Input() @InputBoolean() nzShowRowSelection = false; @Output() readonly nzCheckedChange = new EventEmitter(); @Output() readonly nzSortChange = new EventEmitter(); - @Output() readonly nzSortChangeWithKey = new EventEmitter<{ key: string, value: string | null }>(); + @Output() readonly nzSortChangeWithKey = new EventEmitter<{ key: string; value: string | null }>(); /* tslint:disable-next-line:no-any */ @Output() readonly nzFilterChange = new EventEmitter(); @@ -142,7 +144,7 @@ export class NzThComponent implements OnChanges, OnInit, OnDestroy { } checkSingle(filter: NzThItemInterface): void { - this.singleFilterList.forEach(item => item.checked = item === filter); + this.singleFilterList.forEach(item => (item.checked = item === filter)); } hideDropDown(): void { @@ -190,8 +192,7 @@ export class NzThComponent implements OnChanges, OnInit, OnDestroy { this.cdr.markForCheck(); } - constructor(private cdr: ChangeDetectorRef, private i18n: NzI18nService) { - } + constructor(private cdr: ChangeDetectorRef, private i18n: NzI18nService) {} ngOnInit(): void { this.i18n.localeChange.pipe(takeUntil(this.destroy$)).subscribe(() => { diff --git a/components/table/nz-th.spec.ts b/components/table/nz-th.spec.ts index d83539f4c46..028bbb83c83 100644 --- a/components/table/nz-th.spec.ts +++ b/components/table/nz-th.spec.ts @@ -10,8 +10,8 @@ import { NzThComponent } from './nz-th.component'; describe('nz-th', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTableModule, NzIconTestModule, NoopAnimationsModule ], - declarations: [ NzThTestNzTableComponent, NzThTestTableDefaultFilterComponent ] + imports: [NzTableModule, NzIconTestModule, NoopAnimationsModule], + declarations: [NzThTestNzTableComponent, NzThTestTableDefaultFilterComponent] }); TestBed.compileComponents(); })); @@ -41,13 +41,17 @@ describe('nz-th', () => { it('should checked work', fakeAsync(() => { testComponent.showCheckbox = true; fixture.detectChanges(); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).not.toContain('ant-checkbox-checked'); + expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).not.toContain( + 'ant-checkbox-checked' + ); testComponent.checked = true; fixture.detectChanges(); flush(); fixture.detectChanges(); expect(testComponent.checked).toBe(true); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).toContain('ant-checkbox-checked'); + expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList).toContain( + 'ant-checkbox-checked' + ); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); })); it('should disabled work', () => { @@ -56,12 +60,20 @@ describe('nz-th', () => { testComponent.disabled = true; fixture.detectChanges(); expect(testComponent.checked).toBe(false); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-checked')).toBe(false); + expect( + th.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-checked') + ).toBe(false); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); th.nativeElement.querySelector('.ant-checkbox-wrapper').click(); fixture.detectChanges(); expect(testComponent.checked).toBe(false); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-checked')).toBe(false); + expect( + th.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-checked') + ).toBe(false); expect(testComponent.checkedChange).toHaveBeenCalledTimes(0); }); it('should indeterminate work', () => { @@ -70,10 +82,18 @@ describe('nz-th', () => { fixture.detectChanges(); testComponent.indeterminate = true; fixture.detectChanges(); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-indeterminate')).toBe(true); + expect( + th.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-indeterminate') + ).toBe(true); testComponent.checked = true; fixture.detectChanges(); - expect(th.nativeElement.querySelector('.ant-checkbox-wrapper').firstElementChild!.classList.contains('ant-checkbox-indeterminate')).toBe(true); + expect( + th.nativeElement + .querySelector('.ant-checkbox-wrapper') + .firstElementChild!.classList.contains('ant-checkbox-indeterminate') + ).toBe(true); }); it('should showSort work', () => { fixture.detectChanges(); @@ -176,23 +196,20 @@ describe('nz-th', () => { testComponent.nzThComponent.dropDownVisibleChange(true); fixture.detectChanges(); expect(testComponent.filterChange).toHaveBeenCalledTimes(0); - testComponent.nzThComponent.checkMultiple(testComponent.nzThComponent.multipleFilterList[ 0 ]); + testComponent.nzThComponent.checkMultiple(testComponent.nzThComponent.multipleFilterList[0]); testComponent.nzThComponent.dropDownVisibleChange(false); fixture.detectChanges(); expect(testComponent.nzThComponent.hasFilterValue).toBe(true); - expect(testComponent.filterChange).toHaveBeenCalledWith([ '1' ]); + expect(testComponent.filterChange).toHaveBeenCalledWith(['1']); }); it('should hasFilter change after filters change with multiple', () => { testComponent.showFilter = true; fixture.detectChanges(); - testComponent.nzThComponent.checkMultiple(testComponent.nzThComponent.multipleFilterList[ 0 ]); + testComponent.nzThComponent.checkMultiple(testComponent.nzThComponent.multipleFilterList[0]); testComponent.nzThComponent.search(); fixture.detectChanges(); expect(testComponent.nzThComponent.hasFilterValue).toBe(true); - testComponent.filters = [ - { text: 'filter1', value: '4' }, - { text: 'filter2', value: '3' } - ]; + testComponent.filters = [{ text: 'filter1', value: '4' }, { text: 'filter2', value: '3' }]; fixture.detectChanges(); expect(testComponent.nzThComponent.hasFilterValue).toBe(false); }); @@ -200,14 +217,11 @@ describe('nz-th', () => { testComponent.showFilter = true; testComponent.filterMultiple = false; fixture.detectChanges(); - testComponent.nzThComponent.checkSingle(testComponent.nzThComponent.singleFilterList[ 0 ]); + testComponent.nzThComponent.checkSingle(testComponent.nzThComponent.singleFilterList[0]); testComponent.nzThComponent.search(); fixture.detectChanges(); expect(testComponent.nzThComponent.hasFilterValue).toBe(true); - testComponent.filters = [ - { text: 'filter1', value: '5' }, - { text: 'filter2', value: '3' } - ]; + testComponent.filters = [{ text: 'filter1', value: '5' }, { text: 'filter2', value: '3' }]; fixture.detectChanges(); expect(testComponent.nzThComponent.hasFilterValue).toBe(false); }); @@ -230,7 +244,7 @@ describe('nz-th', () => { testComponent.nzThComponent.dropDownVisibleChange(true); fixture.detectChanges(); expect(testComponent.filterChange).toHaveBeenCalledTimes(0); - testComponent.nzThComponent.checkSingle(testComponent.nzThComponent.singleFilterList[ 0 ]); + testComponent.nzThComponent.checkSingle(testComponent.nzThComponent.singleFilterList[0]); testComponent.nzThComponent.dropDownVisibleChange(false); fixture.detectChanges(); expect(testComponent.filterChange).toHaveBeenCalledWith('1'); @@ -246,7 +260,7 @@ describe('nz-th', () => { it('should be throw error when use specific class name', () => { expect(() => { TestBed.configureTestingModule({ - declarations: [ NzTestDisableThComponent ] + declarations: [NzTestDisableThComponent] }).createComponent(NzTestDisableThComponent); }).toThrow(); }); @@ -316,7 +330,8 @@ describe('nz-th', () => { (nzFilterChange)="filterChange($event)" [nzFilterMultiple]="filterMultiple" > - ` + + ` }) export class NzThTestNzTableComponent { @ViewChild(NzThComponent) nzThComponent: NzThComponent; @@ -335,14 +350,11 @@ export class NzThTestNzTableComponent { showRowSelection = false; selections = [ { - text : 'select one', + text: 'select one', onSelect: jasmine.createSpy('select change') } ]; - filters = [ - { text: 'filter1', value: '1' }, - { text: 'filter2', value: '2' } - ]; + filters = [{ text: 'filter1', value: '1' }, { text: 'filter2', value: '2' }]; filterChange = jasmine.createSpy('filter change'); showFilter = false; filterMultiple = true; @@ -354,65 +366,73 @@ export class NzThTestNzTableComponent { template: ` - - Name - - Age - Address - - + + + Name + + Age + + Address + + - - {{data.name}} - {{data.age}} - {{data.address}} - + + {{ data.name }} + {{ data.age }} + {{ data.address }} + - ` + + ` }) export class NzThTestTableDefaultFilterComponent { - nameList = [ - { text: 'Joe', value: 'Joe', byDefault: true }, - { text: 'Jim', value: 'Jim' } - ]; - addressList = [ - { text: 'London', value: 'London', byDefault: true }, - { text: 'Sidney', value: 'Sidney' } - ]; + nameList = [{ text: 'Joe', value: 'Joe', byDefault: true }, { text: 'Jim', value: 'Jim' }]; + addressList = [{ text: 'London', value: 'London', byDefault: true }, { text: 'Sidney', value: 'Sidney' }]; sortName: string | null = null; sortValue: string | null = null; - listOfSearchName = [ 'Joe', 'London' ]; + listOfSearchName = ['Joe', 'London']; searchAddress: string; - data = [ + data: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = [ { - name : 'John Brown', - age : 32, + name: 'John Brown', + age: 32, address: 'New York No. 1 Lake Park' }, { - name : 'Jim Green', - age : 42, + name: 'Jim Green', + age: 42, address: 'London No. 1 Lake Park' }, { - name : 'Joe Black', - age : 32, + name: 'Joe Black', + age: 32, address: 'Sidney No. 1 Lake Park' }, { - name : 'Jim Red', - age : 32, + name: 'Jim Red', + age: 32, address: 'London No. 2 Lake Park' } ]; - displayData: Array<{ name: string, age: number, address: string }> = []; + displayData: Array<{ name: string; age: number; address: string; [key: string]: string | number }> = []; @ViewChild(NzThComponent) nzThComponent: NzThComponent; - sort(sort: { key: string, value: string }): void { + sort(sort: { key: string; value: string }): void { this.sortName = sort.key; this.sortValue = sort.value; this.search(); @@ -426,16 +446,21 @@ export class NzThTestTableDefaultFilterComponent { search(): void { /** filter data **/ - const filterFunc = (item: { name: string; address: string; age: number }) => ( - this.searchAddress - ? item.address.indexOf(this.searchAddress) !== -1 : true) && (this.listOfSearchName.length - ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) - : true); + const filterFunc = (item: { name: string; address: string; age: number }) => + (this.searchAddress ? item.address.indexOf(this.searchAddress) !== -1 : true) && + (this.listOfSearchName.length ? this.listOfSearchName.some(name => item.name.indexOf(name) !== -1) : true); const data = this.data.filter(item => filterFunc(item)); /** sort data **/ if (this.sortName && this.sortValue) { - // @ts-ignore - this.displayData = data.sort((a, b) => (this.sortValue === 'ascend') ? (a[ this.sortName! ] > b[ this.sortName! ] ? 1 : -1) : (b[ this.sortName! ] > a[ this.sortName! ] ? 1 : -1)); + this.displayData = data.sort((a, b) => + this.sortValue === 'ascend' + ? a[this.sortName!] > b[this.sortName!] + ? 1 + : -1 + : b[this.sortName!] > a[this.sortName!] + ? 1 + : -1 + ); } else { this.displayData = data; } @@ -448,5 +473,4 @@ export class NzThTestTableDefaultFilterComponent { ` }) -export class NzTestDisableThComponent { -} +export class NzTestDisableThComponent {} diff --git a/components/table/nz-thead.component.ts b/components/table/nz-thead.component.ts index 61e486d0bfb..3b0faeb1922 100644 --- a/components/table/nz-thead.component.ts +++ b/components/table/nz-thead.component.ts @@ -1,5 +1,6 @@ import { - AfterContentInit, AfterViewInit, + AfterContentInit, + AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, @@ -25,39 +26,45 @@ import { NzThComponent } from './nz-th.component'; @Component({ // tslint:disable-next-line:component-selector - selector : 'thead:not(.ant-table-thead)', + selector: 'thead:not(.ant-table-thead)', changeDetection: ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-thead.component.html' + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-thead.component.html' }) export class NzTheadComponent implements AfterContentInit, OnDestroy, AfterViewInit { private destroy$ = new Subject(); @ViewChild('contentTemplate') templateRef: TemplateRef; @ContentChildren(NzThComponent, { descendants: true }) listOfNzThComponent: QueryList; @Input() @InputBoolean() nzSingleSort = false; - @Output() readonly nzSortChange = new EventEmitter<{ key: string, value: string }>(); + @Output() readonly nzSortChange = new EventEmitter<{ key: string; value: string }>(); // tslint:disable-next-line:no-any - constructor(@Host() @Optional() public nzTableComponent: NzTableComponent, private elementRef: ElementRef, private renderer: Renderer2) { + constructor( + @Host() @Optional() public nzTableComponent: NzTableComponent, + private elementRef: ElementRef, + private renderer: Renderer2 + ) { if (this.nzTableComponent) { this.nzTableComponent.nzTheadComponent = this; } } ngAfterContentInit(): void { - this.listOfNzThComponent.changes.pipe( - startWith(true), - flatMap(() => merge(...this.listOfNzThComponent.map(th => th.nzSortChangeWithKey))), - takeUntil(this.destroy$) - ).subscribe((data: { key: string, value: string }) => { - this.nzSortChange.emit(data); - if (this.nzSingleSort) { - this.listOfNzThComponent.forEach(th => { - th.nzSort = (th.nzSortKey === data.key ? th.nzSort : null); - th.marForCheck(); - }); - } - }); + this.listOfNzThComponent.changes + .pipe( + startWith(true), + flatMap(() => merge(...this.listOfNzThComponent.map(th => th.nzSortChangeWithKey))), + takeUntil(this.destroy$) + ) + .subscribe((data: { key: string; value: string }) => { + this.nzSortChange.emit(data); + if (this.nzSingleSort) { + this.listOfNzThComponent.forEach(th => { + th.nzSort = th.nzSortKey === data.key ? th.nzSort : null; + th.marForCheck(); + }); + } + }); } ngAfterViewInit(): void { diff --git a/components/table/nz-thead.spec.ts b/components/table/nz-thead.spec.ts index 5b4fb23eab1..24078b851bf 100644 --- a/components/table/nz-thead.spec.ts +++ b/components/table/nz-thead.spec.ts @@ -9,9 +9,9 @@ import { NzTableModule } from './nz-table.module'; describe('nz-thead', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTableModule, NzIconTestModule ], - declarations: [ NzTheadTestNzTableComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NzTableModule, NzIconTestModule], + declarations: [NzTheadTestNzTableComponent], + providers: [NzMeasureScrollbarService] }); TestBed.compileComponents(); })); @@ -29,11 +29,11 @@ describe('nz-thead', () => { fixture.detectChanges(); expect(testComponent.sortChange).toHaveBeenCalledTimes(0); const upButtons = table.nativeElement.querySelectorAll('.ant-table-column-sorters'); - upButtons[ 0 ].click(); + upButtons[0].click(); fixture.detectChanges(); expect(testComponent.sortChange).toHaveBeenCalledTimes(1); expect(upButtons[0].firstElementChild.lastElementChild.classList).toContain('on'); - upButtons[ 1 ].click(); + upButtons[1].click(); fixture.detectChanges(); expect(upButtons[0].firstElementChild.lastElementChild.classList).toContain('on'); expect(upButtons[1].firstElementChild.lastElementChild.classList).toContain('on'); @@ -44,11 +44,11 @@ describe('nz-thead', () => { fixture.detectChanges(); expect(testComponent.sortChange).toHaveBeenCalledTimes(0); const upButtons = table.nativeElement.querySelectorAll('.ant-table-column-sorters'); - upButtons[ 0 ].click(); + upButtons[0].click(); fixture.detectChanges(); expect(testComponent.sortChange).toHaveBeenCalledTimes(1); expect(upButtons[0].firstElementChild.lastElementChild.classList).toContain('on'); - upButtons[ 1 ].click(); + upButtons[1].click(); fixture.detectChanges(); expect(upButtons[0].firstElementChild.lastElementChild.classList).toContain('off'); expect(upButtons[1].firstElementChild.lastElementChild.classList).toContain('on'); diff --git a/components/table/nz-tr.directive.ts b/components/table/nz-tr.directive.ts index 0c0b4042a0a..06d43cab44c 100644 --- a/components/table/nz-tr.directive.ts +++ b/components/table/nz-tr.directive.ts @@ -5,13 +5,11 @@ import { NzTableComponent } from './nz-table.component'; @Directive({ // tslint:disable-next-line:directive-selector selector: 'tr', - host : { + host: { '[class.ant-table-row]': 'nzTableComponent' } }) - export class NzTrDirective { - @Input() set nzExpand(value: boolean) { if (toBoolean(value)) { @@ -23,7 +21,9 @@ export class NzTrDirective { } } - constructor(private elementRef: ElementRef, private renderer: Renderer2, @Host() @Optional() public nzTableComponent: NzTableComponent) { - - } + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + @Host() @Optional() public nzTableComponent: NzTableComponent + ) {} } diff --git a/components/table/nz-tr.spec.ts b/components/table/nz-tr.spec.ts index 7a5c5b07c8a..425c2ac6c3e 100644 --- a/components/table/nz-tr.spec.ts +++ b/components/table/nz-tr.spec.ts @@ -8,9 +8,9 @@ import { NzTrDirective } from './nz-tr.directive'; describe('nz-tr', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTableModule ], - declarations: [ NzTrTestTableComponent, NzTrTestNzTableComponent ], - providers : [ NzMeasureScrollbarService ] + imports: [NzTableModule], + declarations: [NzTrTestTableComponent, NzTrTestNzTableComponent], + providers: [NzMeasureScrollbarService] }); TestBed.compileComponents(); })); @@ -67,10 +67,10 @@ describe('nz-tr', () => { template: ` -
    ` + + ` }) -export class NzTrTestTableComponent { -} +export class NzTrTestTableComponent {} @Component({ selector: 'nz-tr-test-nz-table', diff --git a/components/table/nz-virtual-scroll.directive.ts b/components/table/nz-virtual-scroll.directive.ts index 677e0fed7e6..445b139765c 100644 --- a/components/table/nz-virtual-scroll.directive.ts +++ b/components/table/nz-virtual-scroll.directive.ts @@ -3,9 +3,7 @@ import { Directive, TemplateRef } from '@angular/core'; @Directive({ selector: '[nz-virtual-scroll]' }) - export class NzVirtualScrollDirective { /* tslint:disable-next-line:no-any */ - constructor(public templateRef: TemplateRef<{ $implicit: any, index: number }>) { - } + constructor(public templateRef: TemplateRef<{ $implicit: any; index: number }>) {} } diff --git a/components/tabs/demo/basic.ts b/components/tabs/demo/basic.ts index 1bcdcdec4c8..38d66e4b59b 100644 --- a/components/tabs/demo/basic.ts +++ b/components/tabs/demo/basic.ts @@ -13,7 +13,7 @@ import { Component } from '@angular/core'; Content of Tab Pane 3 - ` + + ` }) -export class NzDemoTabsBasicComponent { -} +export class NzDemoTabsBasicComponent {} diff --git a/components/tabs/demo/card-top.ts b/components/tabs/demo/card-top.ts index a39384262bb..6fb9d617e82 100644 --- a/components/tabs/demo/card-top.ts +++ b/components/tabs/demo/card-top.ts @@ -13,10 +13,10 @@ import { Component } from '@angular/core'; `, - styles : [ - ` + styles: [ + ` :host { - background: #F5F5F5; + background: #f5f5f5; overflow: hidden; padding: 24px; display: block; @@ -49,5 +49,5 @@ import { Component } from '@angular/core'; ] }) export class NzDemoTabsCardTopComponent { - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; } diff --git a/components/tabs/demo/card.ts b/components/tabs/demo/card.ts index ed8796e61d0..9443f0f0de7 100644 --- a/components/tabs/demo/card.ts +++ b/components/tabs/demo/card.ts @@ -4,12 +4,11 @@ import { Component } from '@angular/core'; selector: 'nz-demo-tabs-card', template: ` - - Content of Tab Pane {{ tab }} - - `, - styles : [] + Content of Tab Pane {{ tab }} + + `, + styles: [] }) export class NzDemoTabsCardComponent { - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; } diff --git a/components/tabs/demo/custom-add-trigger.ts b/components/tabs/demo/custom-add-trigger.ts index 5c541ae0140..fedf4b69524 100644 --- a/components/tabs/demo/custom-add-trigger.ts +++ b/components/tabs/demo/custom-add-trigger.ts @@ -13,12 +13,13 @@ import { Component } from '@angular/core';
    Content of {{ tab }} - `, - styles : [] + + `, + styles: [] }) export class NzDemoTabsCustomAddTriggerComponent { index = 0; - tabs = [ 'Tab 1', 'Tab 2' ]; + tabs = ['Tab 1', 'Tab 2']; closeTab(tab: string): void { this.tabs.splice(this.tabs.indexOf(tab), 1); diff --git a/components/tabs/demo/disabled.ts b/components/tabs/demo/disabled.ts index ea972a31b45..42a66a9fb44 100644 --- a/components/tabs/demo/disabled.ts +++ b/components/tabs/demo/disabled.ts @@ -4,26 +4,24 @@ import { Component } from '@angular/core'; selector: 'nz-demo-tabs-disabled', template: ` - + {{ tab.name }} - ` + + ` }) export class NzDemoTabsDisabledComponent { tabs = [ { - name : 'Tab 1', + name: 'Tab 1', disabled: false }, { - name : 'Tab 2', + name: 'Tab 2', disabled: true }, { - name : 'Tab 3', + name: 'Tab 3', disabled: false } ]; diff --git a/components/tabs/demo/editable-card.ts b/components/tabs/demo/editable-card.ts index 48ce1c1fe40..8465a912ea9 100644 --- a/components/tabs/demo/editable-card.ts +++ b/components/tabs/demo/editable-card.ts @@ -20,7 +20,7 @@ import { Component } from '@angular/core'; ` }) export class NzDemoTabsEditableCardComponent { - tabs = [ 'Tab 1', 'Tab 2' ]; + tabs = ['Tab 1', 'Tab 2']; closeTab(tab: string): void { this.tabs.splice(this.tabs.indexOf(tab), 1); diff --git a/components/tabs/demo/extra.ts b/components/tabs/demo/extra.ts index dfcf4894e7a..9d0ff41a289 100644 --- a/components/tabs/demo/extra.ts +++ b/components/tabs/demo/extra.ts @@ -4,9 +4,7 @@ import { Component } from '@angular/core'; selector: 'nz-demo-tabs-extra', template: ` - - Content of tab {{ tab }} - + Content of tab {{ tab }} @@ -14,5 +12,5 @@ import { Component } from '@angular/core'; ` }) export class NzDemoTabsExtraComponent { - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; } diff --git a/components/tabs/demo/icon.ts b/components/tabs/demo/icon.ts index 9785969e44e..85b413fe5c8 100644 --- a/components/tabs/demo/icon.ts +++ b/components/tabs/demo/icon.ts @@ -5,24 +5,23 @@ import { Component } from '@angular/core'; template: ` - - {{ tab.name }} - + {{ tab.name }} {{ tab.name }} - ` + + ` }) export class NzDemoTabsIconComponent { tabs = [ { active: true, - name : 'Tab 1', - icon : 'apple' + name: 'Tab 1', + icon: 'apple' }, { active: false, - name : 'Tab 2', - icon : 'android' + name: 'Tab 2', + icon: 'android' } ]; } diff --git a/components/tabs/demo/lazy.ts b/components/tabs/demo/lazy.ts index f344c8c4f00..4c2dd03b6cc 100644 --- a/components/tabs/demo/lazy.ts +++ b/components/tabs/demo/lazy.ts @@ -21,14 +21,16 @@ import { Component, OnInit } from '@angular/core'; - ` + + ` }) -export class NzDemoTabsLazyComponent { -} +export class NzDemoTabsLazyComponent {} @Component({ selector: 'nz-demo-tab-content-lazy', - template: `lazy` + template: ` + lazy + ` }) export class NzDemoTabContentLazyComponent implements OnInit { ngOnInit(): void { @@ -38,7 +40,9 @@ export class NzDemoTabContentLazyComponent implements OnInit { @Component({ selector: 'nz-demo-tab-content-eagerly', - template: `eagerly` + template: ` + eagerly + ` }) export class NzDemoTabContentEagerlyComponent implements OnInit { ngOnInit(): void { diff --git a/components/tabs/demo/position.ts b/components/tabs/demo/position.ts index 975a446a015..c10154cbef6 100644 --- a/components/tabs/demo/position.ts +++ b/components/tabs/demo/position.ts @@ -6,23 +6,18 @@ import { Component } from '@angular/core';
    Tab position: - - +
    - - Content of tab {{ tab }} - - `, - styles : [] + Content of tab {{ tab }} + + `, + styles: [] }) export class NzDemoTabsPositionComponent { position = 'top'; - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; options = [ { value: 'top', label: 'top' }, { value: 'left', label: 'left' }, diff --git a/components/tabs/demo/size.ts b/components/tabs/demo/size.ts index 8c8d41c8d3b..14866d2ec84 100644 --- a/components/tabs/demo/size.ts +++ b/components/tabs/demo/size.ts @@ -9,13 +9,12 @@ import { Component } from '@angular/core'; - - Content of tab {{ tab }} - - `, - styles : [] + Content of tab {{ tab }} + + `, + styles: [] }) export class NzDemoTabsSizeComponent { size = 'small'; - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; } diff --git a/components/tabs/demo/slide.ts b/components/tabs/demo/slide.ts index eebd2fb0c73..5d785b88d57 100644 --- a/components/tabs/demo/slide.ts +++ b/components/tabs/demo/slide.ts @@ -12,17 +12,20 @@ import { Component, OnInit } from '@angular/core'; style="height:220px;" [nzTabPosition]="nzTabPosition" [(nzSelectedIndex)]="selectedIndex" - (nzSelectChange)="log([$event])"> + (nzSelectChange)="log([$event])" + > + (nzSelect)="log(['select', tab])" + (nzClick)="log(['click', tab])" + (nzDeselect)="log(['deselect', tab])" + > {{ tab.content }} - `, - styles : [] + + `, + styles: [] }) export class NzDemoTabsSlideComponent implements OnInit { tabs: any[] = []; @@ -37,7 +40,7 @@ export class NzDemoTabsSlideComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 11; i++) { this.tabs.push({ - name : `Tab ${i}`, + name: `Tab ${i}`, content: `Content of tab ${i}` }); } diff --git a/components/tabs/nz-tab-body.component.ts b/components/tabs/nz-tab-body.component.ts index cb59e4b7074..913ebeb2ddc 100644 --- a/components/tabs/nz-tab-body.component.ts +++ b/components/tabs/nz-tab-body.component.ts @@ -1,13 +1,13 @@ import { ChangeDetectionStrategy, Component, Input, TemplateRef, ViewEncapsulation } from '@angular/core'; @Component({ - selector : '[nz-tab-body]', + selector: '[nz-tab-body]', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-tab-body.component.html', - host : { - '[class.ant-tabs-tabpane-active]' : 'active', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-tab-body.component.html', + host: { + '[class.ant-tabs-tabpane-active]': 'active', '[class.ant-tabs-tabpane-inactive]': '!active' } }) diff --git a/components/tabs/nz-tab-label.directive.ts b/components/tabs/nz-tab-label.directive.ts index d6cfe385fe1..6030553e292 100644 --- a/components/tabs/nz-tab-label.directive.ts +++ b/components/tabs/nz-tab-label.directive.ts @@ -4,7 +4,7 @@ import { InputBoolean } from '../core/util/convert'; @Directive({ selector: '[nz-tab-label]', - host : { + host: { '[class.ant-tabs-tab-disabled]': 'disabled' } }) diff --git a/components/tabs/nz-tab.component.ts b/components/tabs/nz-tab.component.ts index 8161d197fe0..92cac2add07 100644 --- a/components/tabs/nz-tab.component.ts +++ b/components/tabs/nz-tab.component.ts @@ -1,10 +1,14 @@ import { ChangeDetectionStrategy, - Component, ContentChild, ElementRef, + Component, + ContentChild, + ElementRef, EventEmitter, Input, - OnChanges, OnDestroy, - Output, Renderer2, + OnChanges, + OnDestroy, + Output, + Renderer2, SimpleChanges, TemplateRef, ViewChild, @@ -16,11 +20,11 @@ import { InputBoolean } from '../core/util/convert'; import { NzTabDirective } from './nz-tab.directive'; @Component({ - selector : 'nz-tab', + selector: 'nz-tab', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - templateUrl : './nz-tab.component.html' + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './nz-tab.component.html' }) export class NzTabComponent implements OnChanges, OnDestroy { position: number | null = null; diff --git a/components/tabs/nz-tab.directive.ts b/components/tabs/nz-tab.directive.ts index 4e73f3badfe..9f162503d98 100644 --- a/components/tabs/nz-tab.directive.ts +++ b/components/tabs/nz-tab.directive.ts @@ -1,10 +1,7 @@ -import { - Directive -} from '@angular/core'; +import { Directive } from '@angular/core'; /** Decorates the `ng-template` tags and reads out the template from it. */ @Directive({ selector: '[nz-tab]' }) -export class NzTabDirective { -} +export class NzTabDirective {} diff --git a/components/tabs/nz-tabs-ink-bar.directive.ts b/components/tabs/nz-tabs-ink-bar.directive.ts index 6f184c199fd..e1a74696960 100755 --- a/components/tabs/nz-tabs-ink-bar.directive.ts +++ b/components/tabs/nz-tabs-ink-bar.directive.ts @@ -6,20 +6,17 @@ import { NzTabPositionMode } from './nz-tabset.component'; @Directive({ selector: '[nz-tabs-ink-bar]', - host : { - '[class.ant-tabs-ink-bar-animated]' : 'nzAnimated', + host: { + '[class.ant-tabs-ink-bar-animated]': 'nzAnimated', '[class.ant-tabs-ink-bar-no-animated]': '!nzAnimated' } }) export class NzTabsInkBarDirective { - @Input() @InputBoolean() nzAnimated = false; @Input() nzPositionMode: NzTabPositionMode = 'horizontal'; - constructor(private renderer: Renderer2, - private elementRef: ElementRef, - private ngZone: NgZone) { + constructor(private renderer: Renderer2, private elementRef: ElementRef, private ngZone: NgZone) { renderer.addClass(elementRef.nativeElement, 'ant-tabs-ink-bar'); } @@ -37,17 +34,21 @@ export class NzTabsInkBarDirective { /** when horizontal remove height style and add transform left **/ if (this.nzPositionMode === 'horizontal') { this.renderer.removeStyle(this.elementRef.nativeElement, 'height'); - this.renderer.setStyle(this.elementRef.nativeElement, 'transform', - `translate3d(${this.getLeftPosition(element)}, 0px, 0px)`); - this.renderer.setStyle(this.elementRef.nativeElement, 'width', - this.getElementWidth(element)); + this.renderer.setStyle( + this.elementRef.nativeElement, + 'transform', + `translate3d(${this.getLeftPosition(element)}, 0px, 0px)` + ); + this.renderer.setStyle(this.elementRef.nativeElement, 'width', this.getElementWidth(element)); } else { /** when vertical remove width style and add transform top **/ this.renderer.removeStyle(this.elementRef.nativeElement, 'width'); - this.renderer.setStyle(this.elementRef.nativeElement, 'transform', - `translate3d(0px, ${this.getTopPosition(element)}, 0px)`); - this.renderer.setStyle(this.elementRef.nativeElement, 'height', - this.getElementHeight(element)); + this.renderer.setStyle( + this.elementRef.nativeElement, + 'transform', + `translate3d(0px, ${this.getTopPosition(element)}, 0px)` + ); + this.renderer.setStyle(this.elementRef.nativeElement, 'height', this.getElementHeight(element)); } } diff --git a/components/tabs/nz-tabs-nav.component.ts b/components/tabs/nz-tabs-nav.component.ts index 882ee304f0c..51989382e2e 100644 --- a/components/tabs/nz-tabs-nav.component.ts +++ b/components/tabs/nz-tabs-nav.component.ts @@ -3,7 +3,8 @@ import { Direction, Directionality } from '@angular/cdk/bidi'; import { AfterContentChecked, AfterContentInit, - ChangeDetectionStrategy, ChangeDetectorRef, + ChangeDetectionStrategy, + ChangeDetectorRef, Component, ContentChildren, ElementRef, @@ -31,11 +32,11 @@ const EXAGGERATED_OVERSCROLL = 64; export type ScrollDirection = 'after' | 'before'; @Component({ - selector : '[nz-tabs-nav]', + selector: '[nz-tabs-nav]', preserveWhitespaces: false, - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - templateUrl : './nz-tabs-nav.component.html' + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + templateUrl: './nz-tabs-nav.component.html' }) export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit { private _tabPositionMode: NzTabPositionMode = 'horizontal'; @@ -88,12 +89,13 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit return this._selectedIndex; } - constructor(public elementRef: ElementRef, - private ngZone: NgZone, - private renderer: Renderer2, - private cdr: ChangeDetectorRef, - @Optional() private dir: Directionality) { - } + constructor( + public elementRef: ElementRef, + private ngZone: NgZone, + private renderer: Renderer2, + private cdr: ChangeDetectorRef, + @Optional() private dir: Directionality + ) {} onContentChanges(): void { const textContent = this.elementRef.nativeElement.textContent; @@ -109,7 +111,6 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit this.cdr.markForCheck(); }); } - } scrollHeader(scrollDir: ScrollDirection): void { @@ -119,11 +120,10 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit this.nzOnNextClick.emit(); } // Move the scroll distance one-third the length of the tab list's viewport. - this.scrollDistance += (scrollDir === 'before' ? -1 : 1) * this.viewWidthHeightPix / 3; + this.scrollDistance += ((scrollDir === 'before' ? -1 : 1) * this.viewWidthHeightPix) / 3; } ngAfterContentChecked(): void { - if (this.tabLabelCount !== this.listOfNzTabLabelDirective.length) { if (this.nzShowPagination) { this.updatePagination(); @@ -152,15 +152,16 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit ngAfterContentInit(): void { this.realignInkBar = this.ngZone.runOutsideAngular(() => { const dirChange = this.dir ? this.dir.change : observableOf(null); - const resize = typeof window !== 'undefined' ? - fromEvent(window, 'resize').pipe(auditTime(10)) : - observableOf(null); - return merge(dirChange, resize).pipe(startWith(null)).subscribe(() => { - if (this.nzShowPagination) { - this.updatePagination(); - } - this.alignInkBarToSelectedTab(); - }); + const resize = + typeof window !== 'undefined' ? fromEvent(window, 'resize').pipe(auditTime(10)) : observableOf(null); + return merge(dirChange, resize) + .pipe(startWith(null)) + .subscribe(() => { + if (this.nzShowPagination) { + this.updatePagination(); + } + this.alignInkBarToSelectedTab(); + }); }); } @@ -192,9 +193,7 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit } scrollToLabel(labelIndex: number): void { - const selectedLabel = this.listOfNzTabLabelDirective - ? this.listOfNzTabLabelDirective.toArray()[ labelIndex ] - : null; + const selectedLabel = this.listOfNzTabLabelDirective ? this.listOfNzTabLabelDirective.toArray()[labelIndex] : null; if (selectedLabel) { // The view length is the visible width of the tab labels. @@ -241,7 +240,7 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit * should be called sparingly. */ getMaxScrollDistance(): number { - return (this.tabListScrollWidthHeightPix - this.viewWidthHeightPix) || 0; + return this.tabListScrollWidthHeightPix - this.viewWidthHeightPix || 0; } /** Sets the distance in pixels that the tab header should be transformed in the X-axis. */ @@ -293,9 +292,10 @@ export class NzTabsNavComponent implements AfterContentChecked, AfterContentInit alignInkBarToSelectedTab(): void { if (this.nzType === 'line') { - const selectedLabelWrapper = this.listOfNzTabLabelDirective && this.listOfNzTabLabelDirective.length - ? this.listOfNzTabLabelDirective.toArray()[ this.selectedIndex ].elementRef.nativeElement - : null; + const selectedLabelWrapper = + this.listOfNzTabLabelDirective && this.listOfNzTabLabelDirective.length + ? this.listOfNzTabLabelDirective.toArray()[this.selectedIndex].elementRef.nativeElement + : null; if (this.nzTabsInkBarDirective) { this.nzTabsInkBarDirective.alignToElement(selectedLabelWrapper); } diff --git a/components/tabs/nz-tabs-nav.spec.ts b/components/tabs/nz-tabs-nav.spec.ts index d72c5ba8fc2..e9300e0d8b2 100644 --- a/components/tabs/nz-tabs-nav.spec.ts +++ b/components/tabs/nz-tabs-nav.spec.ts @@ -3,14 +3,7 @@ import { PortalModule } from '@angular/cdk/portal'; import { ScrollDispatchModule, VIEWPORT_RULER_PROVIDER } from '@angular/cdk/scrolling'; import { CommonModule } from '@angular/common'; import { Component, ViewChild, ViewEncapsulation } from '@angular/core'; -import { - async, - discardPeriodicTasks, - fakeAsync, - tick, - ComponentFixture, - TestBed -} from '@angular/core/testing'; +import { async, discardPeriodicTasks, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Subject } from 'rxjs'; @@ -28,11 +21,9 @@ describe('tabs nav', () => { beforeEach(async(() => { dir = 'ltr'; TestBed.configureTestingModule({ - imports : [ CommonModule, PortalModule, NzTabsModule, ScrollDispatchModule ], - declarations: [ - NzTestTabNavComponent - ], - providers : [ + imports: [CommonModule, PortalModule, NzTabsModule, ScrollDispatchModule], + declarations: [NzTestTabNavComponent], + providers: [ VIEWPORT_RULER_PROVIDER, { provide: Directionality, useFactory: () => ({ value: dir, change: change.asObservable() }) } ] @@ -49,7 +40,6 @@ describe('tabs nav', () => { fixture.detectChanges(); appComponent = fixture.componentInstance; - }); it('should scroll click emit', () => { const nav = fixture.debugElement.query(By.directive(NzTabsNavComponent)); @@ -74,8 +64,9 @@ describe('tabs nav', () => { // Focus on the last tab, expect this to be the maximum scroll distance. appComponent.nzTabsNavComponent.selectedIndex = appComponent.tabs.length - 1; fixture.detectChanges(); - expect(appComponent.nzTabsNavComponent.scrollDistance) - .toBe(appComponent.nzTabsNavComponent.getMaxScrollDistance()); + expect(appComponent.nzTabsNavComponent.scrollDistance).toBe( + appComponent.nzTabsNavComponent.getMaxScrollDistance() + ); // Focus on the first tab, expect this to be the maximum scroll distance. appComponent.nzTabsNavComponent.selectedIndex = 0; @@ -102,8 +93,9 @@ describe('tabs nav', () => { // Focus on the last tab, expect this to be the maximum scroll distance. appComponent.nzTabsNavComponent.selectedIndex = appComponent.tabs.length - 1; fixture.detectChanges(); - expect(appComponent.nzTabsNavComponent.scrollDistance) - .toBe(appComponent.nzTabsNavComponent.getMaxScrollDistance()); + expect(appComponent.nzTabsNavComponent.scrollDistance).toBe( + appComponent.nzTabsNavComponent.getMaxScrollDistance() + ); // Focus on the first tab, expect this to be the maximum scroll distance. appComponent.nzTabsNavComponent.selectedIndex = 0; @@ -157,38 +149,33 @@ describe('tabs nav', () => { expect(header.checkPaginationEnabled).toHaveBeenCalled(); discardPeriodicTasks(); })); - }); }); @Component({ - selector : 'nz-test-tab-nav', - template : ` + selector: 'nz-test-tab-nav', + template: `
    -
    -
    - {{tab.label}} + (nzOnPrevClick)="onPrevClick()" + > +
    + {{ tab.label }}
    `, encapsulation: ViewEncapsulation.None, - styleUrls : [ - '../style/index.less', - './style/index.less' - ] + styleUrls: ['../style/index.less', './style/index.less'] }) class NzTestTabNavComponent { selectedIndex: number = 0; - tabs = [ { label: 'tab one' }, { label: 'tab one' }, { label: 'tab one' }, { label: 'tab one' } ]; + tabs = [{ label: 'tab one' }, { label: 'tab one' }, { label: 'tab one' }, { label: 'tab one' }]; dir: Direction = 'ltr'; onNextClick = jasmine.createSpy('next click change'); onPrevClick = jasmine.createSpy('pre click change'); diff --git a/components/tabs/nz-tabs.module.ts b/components/tabs/nz-tabs.module.ts index bbe25366df1..f42f4a93df6 100644 --- a/components/tabs/nz-tabs.module.ts +++ b/components/tabs/nz-tabs.module.ts @@ -13,9 +13,24 @@ import { NzTabsNavComponent } from './nz-tabs-nav.component'; import { NzTabSetComponent } from './nz-tabset.component'; @NgModule({ - declarations: [ NzTabComponent, NzTabDirective, NzTabSetComponent, NzTabsNavComponent, NzTabLabelDirective, NzTabsInkBarDirective, NzTabBodyComponent ], - exports : [ NzTabComponent, NzTabDirective, NzTabSetComponent, NzTabsNavComponent, NzTabLabelDirective, NzTabsInkBarDirective, NzTabBodyComponent ], - imports : [ CommonModule, ObserversModule, NzIconModule, NzAddOnModule ] + declarations: [ + NzTabComponent, + NzTabDirective, + NzTabSetComponent, + NzTabsNavComponent, + NzTabLabelDirective, + NzTabsInkBarDirective, + NzTabBodyComponent + ], + exports: [ + NzTabComponent, + NzTabDirective, + NzTabSetComponent, + NzTabsNavComponent, + NzTabLabelDirective, + NzTabsInkBarDirective, + NzTabBodyComponent + ], + imports: [CommonModule, ObserversModule, NzIconModule, NzAddOnModule] }) -export class NzTabsModule { -} +export class NzTabsModule {} diff --git a/components/tabs/nz-tabs.spec.ts b/components/tabs/nz-tabs.spec.ts index 7c02c4a08f9..6a815e7330d 100644 --- a/components/tabs/nz-tabs.spec.ts +++ b/components/tabs/nz-tabs.spec.ts @@ -9,8 +9,8 @@ import { NzAnimatedInterface, NzTabSetComponent } from './nz-tabset.component'; describe('tabs', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTabsModule ], - declarations: [ NzTestTabsBasicComponent, NzTestTabsTabPositionLeftComponent ] + imports: [NzTabsModule], + declarations: [NzTestTabsBasicComponent, NzTestTabsTabPositionLeftComponent] }); TestBed.compileComponents(); })); @@ -112,21 +112,23 @@ describe('tabs', () => { testComponent.hideAll = true; fixture.detectChanges(); expect(tabs.nativeElement.querySelector('.ant-tabs-tabpane').classList).toContain('ant-tabs-tabpane-inactive'); - expect(tabs.nativeElement.querySelector('.ant-tabs-ink-bar').attributes.getNamedItem('hidden').name).toBe('hidden'); + expect(tabs.nativeElement.querySelector('.ant-tabs-ink-bar').attributes.getNamedItem('hidden').name).toBe( + 'hidden' + ); }); it('should title work', () => { fixture.detectChanges(); const titles = tabs.nativeElement.querySelectorAll('.ant-tabs-tab'); - expect(titles[ 0 ].innerText).toBe('title'); - expect(titles[ 1 ].innerText).toBe('template'); + expect(titles[0].innerText).toBe('title'); + expect(titles[1].innerText).toBe('template'); }); it('should content work', () => { fixture.detectChanges(); const contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); - expect(contents[ 0 ].innerText).toBe('Content 1'); - expect(contents[ 1 ].innerText).toBe('Content 2'); + expect(contents[0].innerText).toBe('Content 1'); + expect(contents[1].innerText).toBe('Content 2'); }); it('should selectedIndex work', fakeAsync(() => { @@ -135,10 +137,10 @@ describe('tabs', () => { fixture.detectChanges(); const titles = tabs.nativeElement.querySelectorAll('.ant-tabs-tab'); const contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -153,10 +155,10 @@ describe('tabs', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).not.toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).not.toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).not.toContain('ant-tabs-tab-active'); + expect(titles[1].classList).toContain('ant-tabs-tab-active'); + expect(contents[0].classList).not.toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(1); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(1); expect(testComponent.selectChange).toHaveBeenCalledTimes(1); @@ -171,10 +173,10 @@ describe('tabs', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(2); expect(testComponent.selectChange).toHaveBeenCalledTimes(2); @@ -192,10 +194,10 @@ describe('tabs', () => { fixture.detectChanges(); const titles = tabs.nativeElement.querySelectorAll('.ant-tabs-tab'); const contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -206,14 +208,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -224,14 +226,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 1 ].click(); + titles[1].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).not.toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).not.toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).not.toContain('ant-tabs-tab-active'); + expect(titles[1].classList).toContain('ant-tabs-tab-active'); + expect(contents[0].classList).not.toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(1); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(1); expect(testComponent.selectChange).toHaveBeenCalledTimes(1); @@ -242,14 +244,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(1); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(2); expect(testComponent.selectChange).toHaveBeenCalledTimes(2); @@ -268,10 +270,10 @@ describe('tabs', () => { fixture.detectChanges(); const titles = tabs.nativeElement.querySelectorAll('.ant-tabs-tab'); const contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -282,14 +284,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -300,14 +302,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 1 ].click(); + titles[1].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -318,14 +320,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -343,10 +345,10 @@ describe('tabs', () => { fixture.detectChanges(); const titles = tabs.nativeElement.querySelectorAll('.ant-tabs-tab'); const contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -357,14 +359,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -375,14 +377,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(0); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 1 ].click(); + titles[1].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).not.toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).not.toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).not.toContain('ant-tabs-tab-active'); + expect(titles[1].classList).toContain('ant-tabs-tab-active'); + expect(contents[0].classList).not.toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(1); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(1); expect(testComponent.selectChange).toHaveBeenCalledTimes(1); @@ -393,14 +395,14 @@ describe('tabs', () => { expect(testComponent.select01).toHaveBeenCalledTimes(1); expect(testComponent.deselect01).toHaveBeenCalledTimes(0); - titles[ 0 ].click(); + titles[0].click(); fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(2); expect(testComponent.selectChange).toHaveBeenCalledTimes(2); @@ -422,10 +424,10 @@ describe('tabs', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -443,12 +445,12 @@ describe('tabs', () => { contents = tabs.nativeElement.querySelectorAll('.ant-tabs-tabpane'); expect(titles.length).toBe(3); expect(contents.length).toBe(3); - expect(titles[ 0 ].classList).toContain('ant-tabs-tab-active'); - expect(titles[ 1 ].classList).not.toContain('ant-tabs-tab-active'); - expect(titles[ 2 ].classList).not.toContain('ant-tabs-tab-active'); - expect(contents[ 0 ].classList).toContain('ant-tabs-tabpane-active'); - expect(contents[ 1 ].classList).not.toContain('ant-tabs-tabpane-active'); - expect(contents[ 2 ].classList).not.toContain('ant-tabs-tabpane-active'); + expect(titles[0].classList).toContain('ant-tabs-tab-active'); + expect(titles[1].classList).not.toContain('ant-tabs-tab-active'); + expect(titles[2].classList).not.toContain('ant-tabs-tab-active'); + expect(contents[0].classList).toContain('ant-tabs-tabpane-active'); + expect(contents[1].classList).not.toContain('ant-tabs-tabpane-active'); + expect(contents[2].classList).not.toContain('ant-tabs-tabpane-active'); expect(testComponent.selectedIndex).toBe(0); expect(testComponent.selectedIndexChange).toHaveBeenCalledTimes(0); expect(testComponent.selectChange).toHaveBeenCalledTimes(0); @@ -471,19 +473,18 @@ describe('tabs', () => { tick(); fixture.detectChanges(); const tabs = fixture.debugElement.query(By.directive(NzTabSetComponent)); - expect(tabs.nativeElement.querySelector('.ant-tabs-nav-container').classList).not.toContain('ant-tabs-nav-container-scrolling'); + expect(tabs.nativeElement.querySelector('.ant-tabs-nav-container').classList).not.toContain( + 'ant-tabs-nav-container-scrolling' + ); })); }); }); @Component({ - selector : 'nz-test-tabs-basic', + selector: 'nz-test-tabs-basic', encapsulation: ViewEncapsulation.None, - styleUrls : [ - '../style/index.less', - './style/index.less' - ], - template : ` + styleUrls: ['../style/index.less', './style/index.less'], + template: ` template extra
    @@ -498,20 +499,24 @@ describe('tabs', () => { [nzTabPosition]="tabPosition" [nzType]="type" [nzTabBarGutter]="tabBarGutter" - [nzHideAll]="hideAll"> + [nzHideAll]="hideAll" + > Content 1 + (nzClick)="click00()" + >Content 1 + [nzDisabled]="disabled" + > Content 2 @@ -521,7 +526,8 @@ describe('tabs', () => { *ngIf="add" (nzDeselect)="deselect02()" (nzSelect)="select02()" - (nzClick)="click02()">add + (nzClick)="click02()" + >add @@ -563,12 +569,10 @@ export class NzTestTabsBasicComponent { selector: 'nz-test-tabs-tab-position-left', template: ` - - Content of tab {{ tab }} - + Content of tab {{ tab }} ` }) export class NzTestTabsTabPositionLeftComponent { - tabs = [ 1, 2, 3 ]; + tabs = [1, 2, 3]; } diff --git a/components/tabs/nz-tabset.component.ts b/components/tabs/nz-tabset.component.ts index d4630f0f20f..fa4d0bcb023 100644 --- a/components/tabs/nz-tabset.component.ts +++ b/components/tabs/nz-tabset.component.ts @@ -1,7 +1,8 @@ /** get some code from https://github.com/angular/material2 */ import { - AfterContentChecked, AfterContentInit, + AfterContentChecked, + AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, @@ -10,7 +11,8 @@ import { ElementRef, EventEmitter, Input, - OnChanges, OnDestroy, + OnChanges, + OnDestroy, OnInit, Output, QueryList, @@ -44,19 +46,22 @@ export type NzTabPositionMode = 'horizontal' | 'vertical'; export type NzTabType = 'line' | 'card'; @Component({ - selector : 'nz-tabset', + selector: 'nz-tabset', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush, - providers : [ NzUpdateHostClassService ], - templateUrl : './nz-tabset.component.html', - styles : [ ` - nz-tabset { - display: block; - } - ` ] + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + providers: [NzUpdateHostClassService], + templateUrl: './nz-tabset.component.html', + styles: [ + ` + nz-tabset { + display: block; + } + ` + ] }) -export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterViewInit, OnChanges, AfterContentInit, OnDestroy { +export class NzTabSetComponent + implements AfterContentChecked, OnInit, AfterViewInit, OnChanges, AfterContentInit, OnDestroy { private indexToSelect: number | null = 0; private el: HTMLElement = this.elementRef.nativeElement; private _selectedIndex: number | null = null; @@ -75,7 +80,7 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView @Input() nzTabPosition: NzTabPosition = 'top'; @Input() nzSize: NzSizeLDSType = 'default'; @Input() nzTabBarGutter: number; - @Input() nzTabBarStyle: { [ key: string ]: string }; + @Input() nzTabBarStyle: { [key: string]: string }; @Input() nzType: NzTabType = 'line'; @Output() readonly nzOnNextClick = new EventEmitter(); @Output() readonly nzOnPrevClick = new EventEmitter(); @@ -92,42 +97,48 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView } get inkBarAnimated(): boolean { - return (this.nzAnimated === true) || ((this.nzAnimated as NzAnimatedInterface).inkBar === true); + return this.nzAnimated === true || (this.nzAnimated as NzAnimatedInterface).inkBar === true; } get tabPaneAnimated(): boolean { - return (this.nzAnimated === true) || ((this.nzAnimated as NzAnimatedInterface).tabPane === true); + return this.nzAnimated === true || (this.nzAnimated as NzAnimatedInterface).tabPane === true; } setPosition(value: NzTabPosition): void { if (this.tabContent) { if (value === 'bottom') { - this.renderer.insertBefore(this.el, this.tabContent.nativeElement, this.nzTabsNavComponent.elementRef.nativeElement); + this.renderer.insertBefore( + this.el, + this.tabContent.nativeElement, + this.nzTabsNavComponent.elementRef.nativeElement + ); } else { - this.renderer.insertBefore(this.el, this.nzTabsNavComponent.elementRef.nativeElement, this.tabContent.nativeElement); + this.renderer.insertBefore( + this.el, + this.nzTabsNavComponent.elementRef.nativeElement, + this.tabContent.nativeElement + ); } } - } setClassMap(): void { - this.nzUpdateHostClassService.updateHostClass(this.el, - { - [ `ant-tabs` ] : true, - [ `ant-tabs-vertical` ] : (this.nzTabPosition === 'left') || (this.nzTabPosition === 'right'), - [ `ant-tabs-${this.nzTabPosition}` ]: this.nzTabPosition, - [ `ant-tabs-no-animation` ] : (this.nzAnimated === false) || ((this.nzAnimated as NzAnimatedInterface).tabPane === false), - [ `ant-tabs-${this.nzType}` ] : this.nzType, - [ `ant-tabs-large` ] : this.nzSize === 'large', - [ `ant-tabs-small` ] : this.nzSize === 'small' - } - ); + this.nzUpdateHostClassService.updateHostClass(this.el, { + [`ant-tabs`]: true, + [`ant-tabs-vertical`]: this.nzTabPosition === 'left' || this.nzTabPosition === 'right', + [`ant-tabs-${this.nzTabPosition}`]: this.nzTabPosition, + [`ant-tabs-no-animation`]: + this.nzAnimated === false || (this.nzAnimated as NzAnimatedInterface).tabPane === false, + [`ant-tabs-${this.nzType}`]: this.nzType, + [`ant-tabs-large`]: this.nzSize === 'large', + [`ant-tabs-small`]: this.nzSize === 'small' + }); } clickLabel(index: number, disabled: boolean): void { if (!disabled) { this.nzSelectedIndex = index; - this.listOfNzTabComponent.toArray()[ index ].nzClick.emit(); + this.listOfNzTabComponent.toArray()[index].nzClick.emit(); } } @@ -135,7 +146,7 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView const event = new NzTabChangeEvent(); event.index = index; if (this.listOfNzTabComponent && this.listOfNzTabComponent.length) { - event.tab = this.listOfNzTabComponent.toArray()[ index ]; + event.tab = this.listOfNzTabComponent.toArray()[index]; this.listOfNzTabComponent.forEach((item, i) => { if (i !== index) { item.nzDeselect.emit(); @@ -158,19 +169,21 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView if (this.tabLabelSubscription) { this.tabLabelSubscription.unsubscribe(); } - this.tabLabelSubscription = merge(...this.listOfNzTabComponent.map(tab => tab.stateChanges)).subscribe(() => this.cdr.markForCheck()); + this.tabLabelSubscription = merge(...this.listOfNzTabComponent.map(tab => tab.stateChanges)).subscribe(() => + this.cdr.markForCheck() + ); } constructor( private renderer: Renderer2, private nzUpdateHostClassService: NzUpdateHostClassService, private elementRef: ElementRef, - private cdr: ChangeDetectorRef) { - } + private cdr: ChangeDetectorRef + ) {} ngOnChanges(changes: SimpleChanges): void { if (changes.nzTabPosition) { - if ((this.nzTabPosition === 'top') || (this.nzTabPosition === 'bottom')) { + if (this.nzTabPosition === 'top' || this.nzTabPosition === 'bottom') { this.tabPositionMode = 'horizontal'; } else { this.tabPositionMode = 'vertical'; @@ -195,7 +208,7 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView if (this.listOfNzTabComponent && this.listOfNzTabComponent.length) { // Don't clamp the `indexToSelect` immediately in the setter because it can happen that // the amount of tabs changes before the actual change detection runs. - const indexToSelect = this.indexToSelect = this.clampTabIndex(this.indexToSelect); + const indexToSelect = (this.indexToSelect = this.clampTabIndex(this.indexToSelect)); // If there is a change in selected index, emit a change event. Should not trigger if // the selected index has not yet been initialized. if (this._selectedIndex !== indexToSelect) { @@ -207,7 +220,7 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView // Changing these values after change detection has run // since the checked content may contain references to them. Promise.resolve().then(() => { - this.listOfNzTabComponent.forEach((tab, index) => tab.isActive = index === indexToSelect); + this.listOfNzTabComponent.forEach((tab, index) => (tab.isActive = index === indexToSelect)); if (!isFirstRun) { this.nzSelectedIndexChange.emit(indexToSelect); @@ -247,7 +260,7 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView const tabs = this.listOfNzTabComponent.toArray(); for (let i = 0; i < tabs.length; i++) { - if (tabs[ i ].isActive) { + if (tabs[i].isActive) { // Assign both to the `_indexToSelect` and `_selectedIndex` so we don't fire a changed // event, otherwise the consumer may end up in an infinite loop in some edge cases like // adding a tab within the `selectedIndexChange` event. @@ -270,5 +283,4 @@ export class NzTabSetComponent implements AfterContentChecked, OnInit, AfterView ngAfterViewInit(): void { this.setPosition(this.nzTabPosition); } - } diff --git a/components/tag/demo/basic.ts b/components/tag/demo/basic.ts index 09c8ef9e039..d8f1eddd3f5 100644 --- a/components/tag/demo/basic.ts +++ b/components/tag/demo/basic.ts @@ -10,10 +10,9 @@ import { Component } from '@angular/core'; Tag 2 Prevent Default `, - styles : [] + styles: [] }) export class NzDemoTagBasicComponent { - onClose(): void { console.log('tag was closed.'); } diff --git a/components/tag/demo/colorful.ts b/components/tag/demo/colorful.ts index 2667359d2b1..b635645c2ed 100644 --- a/components/tag/demo/colorful.ts +++ b/components/tag/demo/colorful.ts @@ -1,9 +1,9 @@ import { Component, ViewEncapsulation } from '@angular/core'; @Component({ - selector : 'nz-demo-tag-colorful', + selector: 'nz-demo-tag-colorful', encapsulation: ViewEncapsulation.None, - template : ` + template: `

    Presets:

    magenta @@ -26,11 +26,12 @@ import { Component, ViewEncapsulation } from '@angular/core'; #108ee9
    `, - styles : [ ` - .ant-tag { - margin-bottom: 8px; - } - ` ] + styles: [ + ` + .ant-tag { + margin-bottom: 8px; + } + ` + ] }) -export class NzDemoTagColorfulComponent { -} +export class NzDemoTagColorfulComponent {} diff --git a/components/tag/demo/control.ts b/components/tag/demo/control.ts index 7f0744636ab..f649145510a 100644 --- a/components/tag/demo/control.ts +++ b/components/tag/demo/control.ts @@ -4,38 +4,38 @@ import { Component, ElementRef, ViewChild } from '@angular/core'; selector: 'nz-demo-tag-control', template: ` + (nzAfterClose)="handleClose(tag)" + > {{ sliceTagName(tag) }} - + New Tag + (keydown.enter)="handleInputConfirm()" + /> `, - styles : [ - `.editable-tag { - background: rgb(255, 255, 255); - border-style: dashed; - }` + styles: [ + ` + .editable-tag { + background: rgb(255, 255, 255); + border-style: dashed; + } + ` ] }) export class NzDemoTagControlComponent { - - tags = [ 'Unremovable', 'Tag 2', 'Tag 3' ]; + tags = ['Unremovable', 'Tag 2', 'Tag 3']; inputVisible = false; inputValue = ''; @ViewChild('inputElement') inputElement: ElementRef; @@ -58,7 +58,7 @@ export class NzDemoTagControlComponent { handleInputConfirm(): void { if (this.inputValue && this.tags.indexOf(this.inputValue) === -1) { - this.tags = [ ...this.tags, this.inputValue ]; + this.tags = [...this.tags, this.inputValue]; } this.inputValue = ''; this.inputVisible = false; diff --git a/components/tag/demo/hot-tags.ts b/components/tag/demo/hot-tags.ts index 316ff49c230..9e300d896cd 100644 --- a/components/tag/demo/hot-tags.ts +++ b/components/tag/demo/hot-tags.ts @@ -1,20 +1,23 @@ import { Component } from '@angular/core'; -const tagsFromServer = [ 'Movie', 'Books', 'Music', 'Sports' ]; +const tagsFromServer = ['Movie', 'Books', 'Music', 'Sports']; @Component({ selector: 'nz-demo-tag-hot-tags', template: ` Categories: - + {{ tag }} `, - styles : [] + styles: [] }) export class NzDemoTagHotTagsComponent { - hotTags = tagsFromServer; selectedTags: string[] = []; diff --git a/components/tag/nz-tag.component.ts b/components/tag/nz-tag.component.ts index ce00a2c5b1b..066eea40b63 100644 --- a/components/tag/nz-tag.component.ts +++ b/components/tag/nz-tag.component.ts @@ -16,21 +16,20 @@ import { NzUpdateHostClassService } from '../core/services/update-host-class.ser import { InputBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-tag', + selector: 'nz-tag', preserveWhitespaces: false, - providers : [ NzUpdateHostClassService ], - animations : [ fadeMotion ], - templateUrl : './nz-tag.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - host : { - '[@fadeMotion]' : '', - '(@fadeMotion.done)' : 'afterAnimation($event)', - '(click)' : 'updateCheckedStatus()', + providers: [NzUpdateHostClassService], + animations: [fadeMotion], + templateUrl: './nz-tag.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + host: { + '[@fadeMotion]': '', + '(@fadeMotion.done)': 'afterAnimation($event)', + '(click)': 'updateCheckedStatus()', '[style.background-color]': 'presetColor? null : nzColor' } }) - export class NzTagComponent implements OnInit, OnChanges { presetColor = false; @Input() nzMode: 'default' | 'closeable' | 'checkable' = 'default'; @@ -45,9 +44,8 @@ export class NzTagComponent implements OnInit, OnChanges { if (!color) { return false; } - return ( - /^(pink|red|yellow|orange|cyan|green|blue|purple|geekblue|magenta|volcano|gold|lime)(-inverse)?$/ - .test(color) + return /^(pink|red|yellow|orange|cyan|green|blue|purple|geekblue|magenta|volcano|gold|lime)(-inverse)?$/.test( + color ); } @@ -55,11 +53,11 @@ export class NzTagComponent implements OnInit, OnChanges { this.presetColor = this.isPresetColor(this.nzColor); const prefix = 'ant-tag'; this.nzUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, { - [ `${prefix}` ] : true, - [ `${prefix}-has-color` ] : this.nzColor && !this.presetColor, - [ `${prefix}-${this.nzColor}` ] : this.presetColor, - [ `${prefix}-checkable` ] : this.nzMode === 'checkable', - [ `${prefix}-checkable-checked` ]: this.nzChecked + [`${prefix}`]: true, + [`${prefix}-has-color`]: this.nzColor && !this.presetColor, + [`${prefix}-${this.nzColor}`]: this.presetColor, + [`${prefix}-checkable`]: this.nzMode === 'checkable', + [`${prefix}-checkable-checked`]: this.nzChecked }); } @@ -84,8 +82,11 @@ export class NzTagComponent implements OnInit, OnChanges { } } - constructor(private renderer: Renderer2, private elementRef: ElementRef, private nzUpdateHostClassService: NzUpdateHostClassService) { - } + constructor( + private renderer: Renderer2, + private elementRef: ElementRef, + private nzUpdateHostClassService: NzUpdateHostClassService + ) {} ngOnInit(): void { this.updateClassMap(); diff --git a/components/tag/nz-tag.module.ts b/components/tag/nz-tag.module.ts index 72774e9ad31..3a83a506ac1 100644 --- a/components/tag/nz-tag.module.ts +++ b/components/tag/nz-tag.module.ts @@ -6,13 +6,8 @@ import { NzIconModule } from '../icon/nz-icon.module'; import { NzTagComponent } from './nz-tag.component'; @NgModule({ - imports : [ CommonModule, FormsModule, NzIconModule ], - declarations: [ - NzTagComponent - ], - exports : [ - NzTagComponent - ] + imports: [CommonModule, FormsModule, NzIconModule], + declarations: [NzTagComponent], + exports: [NzTagComponent] }) -export class NzTagModule { -} +export class NzTagModule {} diff --git a/components/tag/nz-tag.spec.ts b/components/tag/nz-tag.spec.ts index c27ccfbbf74..681cf7ed00c 100644 --- a/components/tag/nz-tag.spec.ts +++ b/components/tag/nz-tag.spec.ts @@ -8,8 +8,8 @@ import { NzTagModule } from './nz-tag.module'; describe('tag', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzTagModule, NoopAnimationsModule ], - declarations: [ NzTestTagBasicComponent, NzTestTagPreventComponent ] + imports: [NzTagModule, NoopAnimationsModule], + declarations: [NzTestTagBasicComponent, NzTestTagPreventComponent] }); TestBed.compileComponents(); })); @@ -116,7 +116,8 @@ describe('tag', () => { [nzColor]="color" (nzCheckedChange)="checkedChange($event)" (nzAfterClose)="afterClose()" - (nzOnClose)="onClose()"> + (nzOnClose)="onClose()" + > Tag 1 ` diff --git a/components/time-picker/demo/disabled-part.ts b/components/time-picker/demo/disabled-part.ts index bdb3af37f6e..34c9735be4c 100644 --- a/components/time-picker/demo/disabled-part.ts +++ b/components/time-picker/demo/disabled-part.ts @@ -3,25 +3,29 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-time-picker-disabled-part', template: ` - + ` }) export class NzDemoTimePickerDisabledPartComponent { disabledHours(): number[] { - return [ 1, 2, 3 ]; + return [1, 2, 3]; } disabledMinutes(hour: number): number[] { if (hour === 4) { - return [ 20, 21, 22, 23, 24, 25 ]; + return [20, 21, 22, 23, 24, 25]; } else { return []; } } disabledSeconds(hour: number, minute: number): number[] { - if ((hour === 5) && (minute === 1)) { - return [ 20, 21, 22, 23, 24, 25 ]; + if (hour === 5 && minute === 1) { + return [20, 21, 22, 23, 24, 25]; } else { return []; } diff --git a/components/time-picker/demo/disabled.ts b/components/time-picker/demo/disabled.ts index 70c54604380..c3f8932f14e 100644 --- a/components/time-picker/demo/disabled.ts +++ b/components/time-picker/demo/disabled.ts @@ -6,5 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTimePickerDisabledComponent { -} +export class NzDemoTimePickerDisabledComponent {} diff --git a/components/time-picker/demo/interval-options.ts b/components/time-picker/demo/interval-options.ts index 173262eb297..00743d31d9a 100644 --- a/components/time-picker/demo/interval-options.ts +++ b/components/time-picker/demo/interval-options.ts @@ -6,5 +6,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTimePickerIntervalOptionsComponent { -} +export class NzDemoTimePickerIntervalOptionsComponent {} diff --git a/components/time-picker/demo/size.ts b/components/time-picker/demo/size.ts index 1da442eb015..34656290a43 100644 --- a/components/time-picker/demo/size.ts +++ b/components/time-picker/demo/size.ts @@ -7,10 +7,12 @@ import { Component } from '@angular/core'; `, - styles : [ - `nz-time-picker { - margin: 0 8px 12px 0; - }` + styles: [ + ` + nz-time-picker { + margin: 0 8px 12px 0; + } + ` ] }) export class NzDemoTimePickerSizeComponent { diff --git a/components/time-picker/nz-time-picker-panel.component.spec.ts b/components/time-picker/nz-time-picker-panel.component.spec.ts index 739f07a17f0..5e03ac97cbe 100644 --- a/components/time-picker/nz-time-picker-panel.component.spec.ts +++ b/components/time-picker/nz-time-picker-panel.component.spec.ts @@ -8,9 +8,9 @@ import { NzTimePickerPanelComponent } from './nz-time-picker-panel.component'; describe('time-picker-panel', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, NzI18nModule ], - schemas : [ NO_ERRORS_SCHEMA ], - declarations: [ NzTimePickerPanelComponent, NzTestTimePanelComponent, NzTestTimePanelDisabledComponent ] + imports: [FormsModule, NzI18nModule], + schemas: [NO_ERRORS_SCHEMA], + declarations: [NzTimePickerPanelComponent, NzTestTimePanelComponent, NzTestTimePanelDisabledComponent] }); TestBed.compileComponents(); })); @@ -56,10 +56,12 @@ describe('time-picker-panel', () => { fixture.detectChanges(); tick(1000); fixture.detectChanges(); - let listOfSelectedLi = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select-option-selected'); - expect(listOfSelectedLi[ 0 ].innerText).toBe('10'); - expect(listOfSelectedLi[ 1 ].innerText).toBe('11'); - expect(listOfSelectedLi[ 2 ].innerText).toBe('12'); + let listOfSelectedLi = panelElement.nativeElement.querySelectorAll( + '.ant-time-picker-panel-select-option-selected' + ); + expect(listOfSelectedLi[0].innerText).toBe('10'); + expect(listOfSelectedLi[1].innerText).toBe('11'); + expect(listOfSelectedLi[2].innerText).toBe('12'); listOfSelectedLi.forEach((li: HTMLElement) => { expect(li.parentElement!.parentElement!.scrollTop).toBe(li.offsetTop); }); @@ -69,9 +71,9 @@ describe('time-picker-panel', () => { fixture.detectChanges(); flush(); listOfSelectedLi = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select-option-selected'); - expect(listOfSelectedLi[ 0 ].innerText).toBe('08'); - expect(listOfSelectedLi[ 1 ].innerText).toBe('09'); - expect(listOfSelectedLi[ 2 ].innerText).toBe('10'); + expect(listOfSelectedLi[0].innerText).toBe('08'); + expect(listOfSelectedLi[1].innerText).toBe('09'); + expect(listOfSelectedLi[2].innerText).toBe('10'); })); it('should select scroll work', fakeAsync(() => { testComponent.value = new Date(0, 0, 0, 8, 9, 10); @@ -79,10 +81,12 @@ describe('time-picker-panel', () => { flush(); fixture.detectChanges(); flush(); - let listOfSelectedLi = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select-option-selected'); - expect(listOfSelectedLi[ 0 ].innerText).toBe('08'); - expect(listOfSelectedLi[ 1 ].innerText).toBe('09'); - expect(listOfSelectedLi[ 2 ].innerText).toBe('10'); + let listOfSelectedLi = panelElement.nativeElement.querySelectorAll( + '.ant-time-picker-panel-select-option-selected' + ); + expect(listOfSelectedLi[0].innerText).toBe('08'); + expect(listOfSelectedLi[1].innerText).toBe('09'); + expect(listOfSelectedLi[2].innerText).toBe('10'); testComponent.nzTimePickerPanelComponent.selectHour({ index: 0, disabled: false }); testComponent.nzTimePickerPanelComponent.selectMinute({ index: 1, disabled: false }); testComponent.nzTimePickerPanelComponent.selectSecond({ index: 2, disabled: false }); @@ -91,24 +95,24 @@ describe('time-picker-panel', () => { fixture.detectChanges(); flush(); listOfSelectedLi = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select-option-selected'); - expect(listOfSelectedLi[ 0 ].innerText).toBe('00'); - expect(listOfSelectedLi[ 1 ].innerText).toBe('01'); - expect(listOfSelectedLi[ 2 ].innerText).toBe('02'); + expect(listOfSelectedLi[0].innerText).toBe('00'); + expect(listOfSelectedLi[1].innerText).toBe('01'); + expect(listOfSelectedLi[2].innerText).toBe('02'); })); it('should step work', () => { fixture.detectChanges(); let listOfSelectContainer = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select'); - expect(listOfSelectContainer[ 0 ].firstElementChild.children.length).toEqual(24); - expect(listOfSelectContainer[ 1 ].firstElementChild.children.length).toEqual(60); - expect(listOfSelectContainer[ 2 ].firstElementChild.children.length).toEqual(60); + expect(listOfSelectContainer[0].firstElementChild.children.length).toEqual(24); + expect(listOfSelectContainer[1].firstElementChild.children.length).toEqual(60); + expect(listOfSelectContainer[2].firstElementChild.children.length).toEqual(60); testComponent.hourStep = 2; testComponent.minuteStep = 15; testComponent.secondStep = 10; fixture.detectChanges(); listOfSelectContainer = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select'); - expect(listOfSelectContainer[ 0 ].firstElementChild.children.length).toEqual(12); - expect(listOfSelectContainer[ 1 ].firstElementChild.children.length).toEqual(4); - expect(listOfSelectContainer[ 2 ].firstElementChild.children.length).toEqual(6); + expect(listOfSelectContainer[0].firstElementChild.children.length).toEqual(12); + expect(listOfSelectContainer[1].firstElementChild.children.length).toEqual(4); + expect(listOfSelectContainer[2].firstElementChild.children.length).toEqual(6); }); }); describe('disabled time-picker-panel', () => { @@ -129,40 +133,39 @@ describe('time-picker-panel', () => { fixture.detectChanges(); flush(); const listOfSelectContainer = panelElement.nativeElement.querySelectorAll('.ant-time-picker-panel-select'); - expect(listOfSelectContainer[ 0 ].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(3); - expect(listOfSelectContainer[ 1 ].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(0); - expect(listOfSelectContainer[ 2 ].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(0); + expect(listOfSelectContainer[0].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(3); + expect(listOfSelectContainer[1].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(0); + expect(listOfSelectContainer[2].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(0); testComponent.nzTimePickerPanelComponent.selectHour({ index: 4, disabled: false }); fixture.detectChanges(); - expect(listOfSelectContainer[ 1 ].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(6); + expect(listOfSelectContainer[1].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(6); testComponent.nzTimePickerPanelComponent.selectHour({ index: 5, disabled: false }); testComponent.nzTimePickerPanelComponent.selectMinute({ index: 1, disabled: false }); fixture.detectChanges(); - expect(listOfSelectContainer[ 2 ].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(6); + expect(listOfSelectContainer[2].querySelectorAll('.ant-time-picker-panel-select-option-disabled').length).toBe(6); testComponent.hideDisabledOptions = true; fixture.detectChanges(); - expect(listOfSelectContainer[ 0 ].firstElementChild.children.length).toBe(21); - expect(listOfSelectContainer[ 2 ].firstElementChild.children.length).toBe(54); + expect(listOfSelectContainer[0].firstElementChild.children.length).toBe(21); + expect(listOfSelectContainer[2].firstElementChild.children.length).toBe(54); })); }); }); @Component({ - selector : 'nz-test-time-panel', + selector: 'nz-test-time-panel', encapsulation: ViewEncapsulation.None, - template : ` + template: ` - `, - styleUrls : [ - '../style/index.less', - './style/index.less' - ] + [nzHourStep]="hourStep" + > + + `, + styleUrls: ['../style/index.less', './style/index.less'] }) export class NzTestTimePanelComponent { secondStep = 1; @@ -175,9 +178,9 @@ export class NzTestTimePanelComponent { } @Component({ - selector : 'nz-test-time-panel-disabled', + selector: 'nz-test-time-panel-disabled', encapsulation: ViewEncapsulation.None, - template : ` + template: ` - `, - styleUrls : [ - '../style/index.less', - './style/index.less' - ] + [nzHourStep]="hourStep" + > + + `, + styleUrls: ['../style/index.less', './style/index.less'] }) export class NzTestTimePanelDisabledComponent { inDatePicker = false; @@ -208,20 +210,20 @@ export class NzTestTimePanelDisabledComponent { format = 'HH:mm:ss'; disabledHours(): number[] { - return [ 1, 2, 3 ]; + return [1, 2, 3]; } disabledMinutes(hour: number): number[] { if (hour === 4) { - return [ 20, 21, 22, 23, 24, 25 ]; + return [20, 21, 22, 23, 24, 25]; } else { return []; } } disabledSeconds(hour: number, minute: number): number[] { - if ((hour === 5) && (minute === 1)) { - return [ 20, 21, 22, 23, 24, 25 ]; + if (hour === 5 && minute === 1) { + return [20, 21, 22, 23, 24, 25]; } else { return []; } diff --git a/components/time-picker/nz-time-picker-panel.component.ts b/components/time-picker/nz-time-picker-panel.component.ts index 402bde05028..6e3c38040b8 100644 --- a/components/time-picker/nz-time-picker-panel.component.ts +++ b/components/time-picker/nz-time-picker-panel.component.ts @@ -1,7 +1,8 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, DebugElement, + Component, + DebugElement, ElementRef, Input, OnDestroy, @@ -30,12 +31,9 @@ export type NzTimePickerUnit = 'hour' | 'minute' | 'second'; @Component({ encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-time-picker-panel', + selector: 'nz-time-picker-panel', templateUrl: './nz-time-picker-panel.component.html', - providers : [ - UpdateCls, - { provide: NG_VALUE_ACCESSOR, useExisting: NzTimePickerPanelComponent, multi: true } - ] + providers: [UpdateCls, { provide: NG_VALUE_ACCESSOR, useExisting: NzTimePickerPanelComponent, multi: true }] }) export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, OnDestroy { private _nzHourStep = 1; @@ -57,9 +55,9 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, minuteEnabled = true; secondEnabled = true; enabledColumns = 3; - hourRange: ReadonlyArray<{ index: number, disabled: boolean }>; - minuteRange: ReadonlyArray<{ index: number, disabled: boolean }>; - secondRange: ReadonlyArray<{ index: number, disabled: boolean }>; + hourRange: ReadonlyArray<{ index: number; disabled: boolean }>; + minuteRange: ReadonlyArray<{ index: number; disabled: boolean }>; + secondRange: ReadonlyArray<{ index: number; disabled: boolean }>; @ViewChild(NzTimeValueAccessorDirective) nzTimeValueAccessorDirective: NzTimeValueAccessorDirective; @ViewChild('hourListElement') hourListElement: DebugElement; @ViewChild('minuteListElement') minuteListElement: DebugElement; @@ -213,32 +211,30 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, buildHours(): void { this.hourRange = makeRange(24, this.nzHourStep).map(r => { - return { - index : r, - disabled: this.nzDisabledHours && (this.nzDisabledHours().indexOf(r) !== -1) - }; - } - ); + return { + index: r, + disabled: this.nzDisabledHours && this.nzDisabledHours().indexOf(r) !== -1 + }; + }); } buildMinutes(): void { this.minuteRange = makeRange(60, this.nzMinuteStep).map(r => { - return { - index : r, - disabled: this.nzDisabledMinutes && (this.nzDisabledMinutes(this.time.hours!).indexOf(r) !== -1) - }; - } - ); + return { + index: r, + disabled: this.nzDisabledMinutes && this.nzDisabledMinutes(this.time.hours!).indexOf(r) !== -1 + }; + }); } buildSeconds(): void { this.secondRange = makeRange(60, this.nzSecondStep).map(r => { - return { - index : r, - disabled: this.nzDisabledSeconds && (this.nzDisabledSeconds(this.time.hours!, this.time.minutes!).indexOf(r) !== -1) - }; - } - ); + return { + index: r, + disabled: + this.nzDisabledSeconds && this.nzDisabledSeconds(this.time.hours!, this.time.minutes!).indexOf(r) !== -1 + }; + }); } buildTimes(): void { @@ -247,7 +243,7 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, this.buildSeconds(); } - selectHour(hour: { index: number, disabled: boolean }): void { + selectHour(hour: { index: number; disabled: boolean }): void { this.time.setHours(hour.index, hour.disabled); this.scrollToSelected(this.hourListElement.nativeElement, hour.index, 120, 'hour'); @@ -259,7 +255,7 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, } } - selectMinute(minute: { index: number, disabled: boolean }): void { + selectMinute(minute: { index: number; disabled: boolean }): void { this.time.setMinutes(minute.index, minute.disabled); this.scrollToSelected(this.minuteListElement.nativeElement, minute.index, 120, 'minute'); if (this._disabledSeconds) { @@ -267,14 +263,15 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, } } - selectSecond(second: { index: number, disabled: boolean }): void { + selectSecond(second: { index: number; disabled: boolean }): void { this.time.setSeconds(second.index, second.disabled); this.scrollToSelected(this.secondListElement.nativeElement, second.index, 120, 'second'); } scrollToSelected(instance: HTMLElement, index: number, duration: number = 0, unit: NzTimePickerUnit): void { const transIndex = this.translateIndex(index, unit); - const currentOption = (instance.children[ 0 ].children[ transIndex ] || instance.children[ 0 ].children[ 0 ]) as HTMLElement; + const currentOption = (instance.children[0].children[transIndex] || + instance.children[0].children[0]) as HTMLElement; this.scrollTo(instance, currentOption.offsetTop, duration); } @@ -285,7 +282,8 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, } else if (unit === 'minute') { const disabledMinutes = this.nzDisabledMinutes && this.nzDisabledMinutes(this.time.hours!); return this.calcIndex(disabledMinutes, this.minuteRange.map(item => item.index).indexOf(index)); - } else { // second + } else { + // second const disabledSeconds = this.nzDisabledSeconds && this.nzDisabledSeconds(this.time.hours!, this.time.minutes!); return this.calcIndex(disabledSeconds, this.secondRange.map(item => item.index).indexOf(index)); } @@ -297,7 +295,7 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, return; } const difference = to - element.scrollTop; - const perTick = difference / duration * 10; + const perTick = (difference / duration) * 10; reqAnimFrame(() => { element.scrollTop = element.scrollTop + perTick; @@ -310,9 +308,12 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, calcIndex(array: number[], index: number): number { if (array && array.length && this.nzHideDisabledOptions) { - return index - array.reduce((pre, value) => { - return pre + (value < index ? 1 : 0); - }, 0); + return ( + index - + array.reduce((pre, value) => { + return pre + (value < index ? 1 : 0); + }, 0) + ); } else { return index; } @@ -332,23 +333,27 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, private setClassMap(): void { this.updateCls.updateHostClass(this.element.nativeElement, { - [`${this.prefixCls}`] : true, - [`${this.prefixCls}-column-${this.enabledColumns}`] : this.nzInDatePicker ? false : true, - [`${this.prefixCls}-narrow`] : this.enabledColumns < 3, - [`${this.prefixCls}-placement-bottomLeft`] : this.nzInDatePicker ? false : true + [`${this.prefixCls}`]: true, + [`${this.prefixCls}-column-${this.enabledColumns}`]: this.nzInDatePicker ? false : true, + [`${this.prefixCls}-narrow`]: this.enabledColumns < 3, + [`${this.prefixCls}-placement-bottomLeft`]: this.nzInDatePicker ? false : true }); } - isSelectedHour(hour: { index: number, disabled: boolean }): boolean { - return (hour.index === this.time.hours) || (!isNotNil(this.time.hours) && (hour.index === this.time.defaultHours)); + isSelectedHour(hour: { index: number; disabled: boolean }): boolean { + return hour.index === this.time.hours || (!isNotNil(this.time.hours) && hour.index === this.time.defaultHours); } - isSelectedMinute(minute: { index: number, disabled: boolean }): boolean { - return (minute.index === this.time.minutes) || (!isNotNil(this.time.minutes) && (minute.index === this.time.defaultMinutes)); + isSelectedMinute(minute: { index: number; disabled: boolean }): boolean { + return ( + minute.index === this.time.minutes || (!isNotNil(this.time.minutes) && minute.index === this.time.defaultMinutes) + ); } - isSelectedSecond(second: { index: number, disabled: boolean }): boolean { - return (second.index === this.time.seconds) || (!isNotNil(this.time.seconds) && (second.index === this.time.defaultSeconds)); + isSelectedSecond(second: { index: number; disabled: boolean }): boolean { + return ( + second.index === this.time.seconds || (!isNotNil(this.time.seconds) && second.index === this.time.defaultSeconds) + ); } initPosition(): void { @@ -377,8 +382,7 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, }); } - constructor(private element: ElementRef, private updateCls: UpdateCls, private cdr: ChangeDetectorRef) { - } + constructor(private element: ElementRef, private updateCls: UpdateCls, private cdr: ChangeDetectorRef) {} ngOnInit(): void { if (this.nzInDatePicker) { @@ -413,5 +417,4 @@ export class NzTimePickerPanelComponent implements ControlValueAccessor, OnInit, registerOnTouched(fn: () => void): void { this.onTouch = fn; } - } diff --git a/components/time-picker/nz-time-picker.component.spec.ts b/components/time-picker/nz-time-picker.component.spec.ts index aae34ddba7c..8e6652178f4 100644 --- a/components/time-picker/nz-time-picker.component.spec.ts +++ b/components/time-picker/nz-time-picker.component.spec.ts @@ -16,16 +16,16 @@ describe('time-picker', () => { let overlayContainer: OverlayContainer; beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, FormsModule, NzI18nModule, NzTimePickerModule ], - schemas : [ NO_ERRORS_SCHEMA ], - declarations: [ NzTestTimePickerComponent ] + imports: [NoopAnimationsModule, FormsModule, NzI18nModule, NzTimePickerModule], + schemas: [NO_ERRORS_SCHEMA], + declarations: [NzTestTimePickerComponent] }); TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -47,7 +47,9 @@ describe('time-picker', () => { fixture.detectChanges(); testComponent.autoFocus = true; fixture.detectChanges(); - expect(timeElement.nativeElement.querySelector('input').attributes.getNamedItem('autofocus').name).toBe('autofocus'); + expect(timeElement.nativeElement.querySelector('input').attributes.getNamedItem('autofocus').name).toBe( + 'autofocus' + ); testComponent.autoFocus = false; fixture.detectChanges(); expect(timeElement.nativeElement.querySelector('input').attributes.getNamedItem('autofocus')).toBe(null); @@ -101,7 +103,14 @@ describe('time-picker', () => { @Component({ selector: 'nz-test-time-picker', template: ` - ` + + ` }) export class NzTestTimePickerComponent { open = false; diff --git a/components/time-picker/nz-time-picker.component.ts b/components/time-picker/nz-time-picker.component.ts index d9779ffdcbc..1eb785b68ec 100644 --- a/components/time-picker/nz-time-picker.component.ts +++ b/components/time-picker/nz-time-picker.component.ts @@ -21,15 +21,12 @@ import { isNotNil } from '../core/util/check'; import { toBoolean } from '../core/util/convert'; @Component({ - encapsulation : ViewEncapsulation.None, + encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - selector : 'nz-time-picker', - templateUrl : './nz-time-picker.component.html', - animations : [ slideMotion ], - providers : [ - UpdateCls, - { provide: NG_VALUE_ACCESSOR, useExisting: NzTimePickerComponent, multi: true } - ] + selector: 'nz-time-picker', + templateUrl: './nz-time-picker.component.html', + animations: [slideMotion], + providers: [UpdateCls, { provide: NG_VALUE_ACCESSOR, useExisting: NzTimePickerComponent, multi: true }] }) export class NzTimePickerComponent implements ControlValueAccessor, OnInit, AfterViewInit { private _disabled = false; @@ -41,14 +38,16 @@ export class NzTimePickerComponent implements ControlValueAccessor, OnInit, Afte private _hideDisabledOptions = false; isInit = false; origin: CdkOverlayOrigin; - overlayPositions: ConnectionPositionPair[] = [ { - originX : 'start', - originY : 'top', - overlayX: 'end', - overlayY: 'top', - offsetX : 0, - offsetY : 0 - } ]; + overlayPositions: ConnectionPositionPair[] = [ + { + originX: 'start', + originY: 'top', + overlayX: 'end', + overlayY: 'top', + offsetX: 0, + offsetY: 0 + } + ]; @ViewChild('inputElement') inputRef: ElementRef; @Input() nzSize: string | null = null; @Input() nzHourStep = 1; @@ -152,8 +151,8 @@ export class NzTimePickerComponent implements ControlValueAccessor, OnInit, Afte private setClassMap(): void { this.updateCls.updateHostClass(this.element.nativeElement, { - [ `ant-time-picker` ] : true, - [ `ant-time-picker-${this.nzSize}` ]: isNotNil(this.nzSize) + [`ant-time-picker`]: true, + [`ant-time-picker-${this.nzSize}`]: isNotNil(this.nzSize) }); } @@ -169,11 +168,12 @@ export class NzTimePickerComponent implements ControlValueAccessor, OnInit, Afte } } - constructor(private element: ElementRef, - private renderer: Renderer2, - private updateCls: UpdateCls, - public cdr: ChangeDetectorRef) { - } + constructor( + private element: ElementRef, + private renderer: Renderer2, + private updateCls: UpdateCls, + public cdr: ChangeDetectorRef + ) {} ngOnInit(): void { this.setClassMap(); diff --git a/components/time-picker/nz-time-picker.module.ts b/components/time-picker/nz-time-picker.module.ts index 97a338679b9..dd77b869a16 100644 --- a/components/time-picker/nz-time-picker.module.ts +++ b/components/time-picker/nz-time-picker.module.ts @@ -10,17 +10,9 @@ import { NzTimePickerComponent } from './nz-time-picker.component'; import { NzTimeValueAccessorDirective } from './nz-time-value-accessor.directive'; @NgModule({ - declarations : [ - NzTimePickerComponent, - NzTimePickerPanelComponent, - NzTimeValueAccessorDirective - ], - exports : [ - NzTimePickerPanelComponent, - NzTimePickerComponent - ], - imports : [ CommonModule, FormsModule, NzI18nModule, OverlayModule, NzIconModule, NzOverlayModule ], + declarations: [NzTimePickerComponent, NzTimePickerPanelComponent, NzTimeValueAccessorDirective], + exports: [NzTimePickerPanelComponent, NzTimePickerComponent], + imports: [CommonModule, FormsModule, NzI18nModule, OverlayModule, NzIconModule, NzOverlayModule], entryComponents: [] }) -export class NzTimePickerModule { -} +export class NzTimePickerModule {} diff --git a/components/time-picker/nz-time-value-accessor.directive.spec.ts b/components/time-picker/nz-time-value-accessor.directive.spec.ts index 299855c2210..8e6869d17f1 100644 --- a/components/time-picker/nz-time-value-accessor.directive.spec.ts +++ b/components/time-picker/nz-time-value-accessor.directive.spec.ts @@ -15,8 +15,8 @@ registerLocaleData(zh); describe('input-time', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ FormsModule, NzI18nModule ], - declarations: [ NzTimeValueAccessorDirective, NzTestTimeInputComponent ] + imports: [FormsModule, NzI18nModule], + declarations: [NzTimeValueAccessorDirective, NzTestTimeInputComponent] }); TestBed.compileComponents(); })); @@ -66,7 +66,9 @@ describe('input-time', () => { @Component({ selector: 'nz-test-time-input', - template: `` + template: ` + + ` }) export class NzTestTimeInputComponent { @ViewChild(NzTimeValueAccessorDirective) nzTimeValueAccessorDirective: NzTimeValueAccessorDirective; diff --git a/components/time-picker/nz-time-value-accessor.directive.ts b/components/time-picker/nz-time-value-accessor.directive.ts index 8e16bb68726..a7b3d22d2a3 100644 --- a/components/time-picker/nz-time-value-accessor.directive.ts +++ b/components/time-picker/nz-time-value-accessor.directive.ts @@ -3,13 +3,10 @@ import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { DateHelperService } from '../i18n/date-helper.service'; @Directive({ - selector : 'input[nzTime]', - providers: [ - { provide: NG_VALUE_ACCESSOR, useExisting: NzTimeValueAccessorDirective, multi: true } - ] + selector: 'input[nzTime]', + providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: NzTimeValueAccessorDirective, multi: true }] }) export class NzTimeValueAccessorDirective implements ControlValueAccessor { - private _onChange: (value: Date) => void; private _onTouch: () => void; @Input() nzTime: string; @@ -42,8 +39,7 @@ export class NzTimeValueAccessorDirective implements ControlValueAccessor { this.elementRef.nativeElement.setSelectionRange(0, this.elementRef.nativeElement.value.length); } - constructor(private dateHelper: DateHelperService, private elementRef: ElementRef) { - } + constructor(private dateHelper: DateHelperService, private elementRef: ElementRef) {} writeValue(value: Date): void { this.elementRef.nativeElement.value = this.dateHelper.format(value, this.nzTime); @@ -56,5 +52,4 @@ export class NzTimeValueAccessorDirective implements ControlValueAccessor { registerOnTouched(fn: () => void): void { this._onTouch = fn; } - } diff --git a/components/time-picker/time-holder.spec.ts b/components/time-picker/time-holder.spec.ts index 9e0d88f554a..a65566d0e11 100644 --- a/components/time-picker/time-holder.spec.ts +++ b/components/time-picker/time-holder.spec.ts @@ -13,7 +13,10 @@ describe('time holder', () => { }); it('should set hours', () => { - const holder = new TimeHolder().setHours(23, false).setMinutes(10, false).setSeconds(20, false); + const holder = new TimeHolder() + .setHours(23, false) + .setMinutes(10, false) + .setSeconds(20, false); const date = new Date(); date.setHours(23); date.setMinutes(10); @@ -22,8 +25,14 @@ describe('time holder', () => { }); it('should ignore disabled', () => { - const holder = new TimeHolder().setHours(23, false).setMinutes(10, false).setSeconds(20, false); - holder.setHours(0, true).setMinutes(0, true).setSeconds(0, true); + const holder = new TimeHolder() + .setHours(23, false) + .setMinutes(10, false) + .setSeconds(20, false); + holder + .setHours(0, true) + .setMinutes(0, true) + .setSeconds(0, true); const date = new Date(); date.setHours(23); date.setMinutes(10); @@ -65,5 +74,4 @@ describe('time holder', () => { holder.setMinutes(23, false); expect(holder.value).toEqual(new Date(2001, 10, 1, 23, 23, 20)); }); - }); diff --git a/components/time-picker/time-holder.ts b/components/time-picker/time-holder.ts index f65db42fce4..031ad43a470 100644 --- a/components/time-picker/time-holder.ts +++ b/components/time-picker/time-holder.ts @@ -176,7 +176,5 @@ export class TimeHolder { return this._defaultOpenValue.getSeconds(); } - constructor() { - } - + constructor() {} } diff --git a/components/timeline/demo/alternate.ts b/components/timeline/demo/alternate.ts index f63fe39ec49..0607070f224 100644 --- a/components/timeline/demo/alternate.ts +++ b/components/timeline/demo/alternate.ts @@ -6,7 +6,11 @@ import { Component } from '@angular/core'; Create a services site 2015-09-01 Solve initial network problems 2015-09-01 - Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. + Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem + aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt + explicabo. Network problems being solved 2015-09-01 Create a services site 2015-09-01 Technical testing 2015-09-01 @@ -16,5 +20,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTimelineAlternateComponent { -} +export class NzDemoTimelineAlternateComponent {} diff --git a/components/timeline/demo/basic.ts b/components/timeline/demo/basic.ts index 715fa6a21a1..dc876b75979 100644 --- a/components/timeline/demo/basic.ts +++ b/components/timeline/demo/basic.ts @@ -8,7 +8,7 @@ import { Component } from '@angular/core'; Solve initial network problems 2015-09-01 Technical testing 2015-09-01 Network problems being solved 2015-09-01 - ` + + ` }) -export class NzDemoTimelineBasicComponent { -} +export class NzDemoTimelineBasicComponent {} diff --git a/components/timeline/demo/color.ts b/components/timeline/demo/color.ts index 51a0295c18a..66b6872513a 100644 --- a/components/timeline/demo/color.ts +++ b/components/timeline/demo/color.ts @@ -16,8 +16,8 @@ import { Component } from '@angular/core';

    Technical testing 2

    Technical testing 3 2015-09-01

    - `, - styles : [] + + `, + styles: [] }) -export class NzDemoTimelineColorComponent { -} +export class NzDemoTimelineColorComponent {} diff --git a/components/timeline/demo/custom.ts b/components/timeline/demo/custom.ts index 0e2f88203e2..d482aa532c1 100644 --- a/components/timeline/demo/custom.ts +++ b/components/timeline/demo/custom.ts @@ -14,6 +14,4 @@ import { Component } from '@angular/core'; ` }) - -export class NzDemoTimelineCustomComponent { -} +export class NzDemoTimelineCustomComponent {} diff --git a/components/timeline/demo/pending.ts b/components/timeline/demo/pending.ts index d20cdff1af3..bf77620def9 100644 --- a/components/timeline/demo/pending.ts +++ b/components/timeline/demo/pending.ts @@ -11,7 +11,6 @@ import { Component } from '@angular/core'; ` }) - export class NzDemoTimelinePendingComponent { reverse = false; diff --git a/components/timeline/demo/right.ts b/components/timeline/demo/right.ts index 15067157a0e..edfd92b33d8 100644 --- a/components/timeline/demo/right.ts +++ b/components/timeline/demo/right.ts @@ -14,5 +14,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTimelineRightComponent { -} +export class NzDemoTimelineRightComponent {} diff --git a/components/timeline/nz-timeline-item.component.ts b/components/timeline/nz-timeline-item.component.ts index 7c3ca0705fc..e0e6f5eb3e0 100644 --- a/components/timeline/nz-timeline-item.component.ts +++ b/components/timeline/nz-timeline-item.component.ts @@ -3,7 +3,8 @@ import { ChangeDetectorRef, Component, ElementRef, - Input, OnChanges, + Input, + OnChanges, OnInit, Renderer2, SimpleChanges, @@ -15,11 +16,11 @@ import { import { NzTimelineMode } from './nz-timeline.component'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - selector : 'nz-timeline-item, [nz-timeline-item]', - templateUrl : './nz-timeline-item.component.html' + selector: 'nz-timeline-item, [nz-timeline-item]', + templateUrl: './nz-timeline-item.component.html' }) export class NzTimelineItemComponent implements OnInit, OnChanges { @ViewChild('liTemplate') liTemplate: ElementRef; @@ -46,7 +47,7 @@ export class NzTimelineItemComponent implements OnInit, OnChanges { } private tryUpdateCustomColor(): void { - const defaultColors = [ 'blue', 'red', 'green' ]; + const defaultColors = ['blue', 'red', 'green']; const circle = this.liTemplate.nativeElement.querySelector('.ant-timeline-item-head'); if (defaultColors.indexOf(this.nzColor) === -1) { this.renderer.setStyle(circle, 'border-color', this.nzColor); diff --git a/components/timeline/nz-timeline.component.ts b/components/timeline/nz-timeline.component.ts index 73a1f4d13c0..db361d65deb 100644 --- a/components/timeline/nz-timeline.component.ts +++ b/components/timeline/nz-timeline.component.ts @@ -24,11 +24,11 @@ import { NzTimelineItemComponent } from './nz-timeline-item.component'; export type NzTimelineMode = 'left' | 'alternate' | 'right'; @Component({ - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, preserveWhitespaces: false, - selector : 'nz-timeline', - templateUrl : './nz-timeline.component.html' + selector: 'nz-timeline', + templateUrl: './nz-timeline.component.html' }) export class NzTimelineComponent implements AfterContentInit, OnChanges, OnDestroy { @ViewChild('timeline') timeline: ElementRef; @@ -54,7 +54,11 @@ export class NzTimelineComponent implements AfterContentInit, OnChanges, OnDestr if (modeChanges && (modeChanges.previousValue !== modeChanges.currentValue || modeChanges.isFirstChange())) { this.updateChildren(); } - if (reverseChanges && reverseChanges.previousValue !== reverseChanges.currentValue && !reverseChanges.isFirstChange()) { + if ( + reverseChanges && + reverseChanges.previousValue !== reverseChanges.currentValue && + !reverseChanges.isFirstChange() + ) { this.reverseChildTimelineDots(); } if (pendingChanges) { @@ -81,11 +85,14 @@ export class NzTimelineComponent implements AfterContentInit, OnChanges, OnDestr const length = this.listOfTimeLine.length; this.listOfTimeLine.toArray().forEach((item, index) => { item.isLast = !this.nzReverse ? index === length - 1 : index === 0; - item.position = this.nzMode === 'left' || !this.nzMode - ? undefined - : this.nzMode === 'right' + item.position = + this.nzMode === 'left' || !this.nzMode + ? undefined + : this.nzMode === 'right' ? 'right' - : this.nzMode === 'alternate' && index % 2 === 0 ? 'left' : 'right'; + : this.nzMode === 'alternate' && index % 2 === 0 + ? 'left' + : 'right'; item.detectChanges(); }); this.cdr.markForCheck(); diff --git a/components/timeline/nz-timeline.module.ts b/components/timeline/nz-timeline.module.ts index cbbd00c2059..ccce08dfdca 100644 --- a/components/timeline/nz-timeline.module.ts +++ b/components/timeline/nz-timeline.module.ts @@ -8,9 +8,8 @@ import { NzTimelineItemComponent } from './nz-timeline-item.component'; import { NzTimelineComponent } from './nz-timeline.component'; @NgModule({ - declarations: [ NzTimelineItemComponent, NzTimelineComponent ], - exports : [ NzTimelineItemComponent, NzTimelineComponent ], - imports : [ CommonModule, NzIconModule, NzAddOnModule ] + declarations: [NzTimelineItemComponent, NzTimelineComponent], + exports: [NzTimelineItemComponent, NzTimelineComponent], + imports: [CommonModule, NzIconModule, NzAddOnModule] }) -export class NzTimelineModule { -} +export class NzTimelineModule {} diff --git a/components/timeline/nz-timeline.spec.ts b/components/timeline/nz-timeline.spec.ts index 8206749231a..c2c63e35645 100644 --- a/components/timeline/nz-timeline.spec.ts +++ b/components/timeline/nz-timeline.spec.ts @@ -9,8 +9,8 @@ import { NzTimelineModule } from './nz-timeline.module'; describe('timeline', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzTimelineModule ], - declarations: [ NzTestTimelineBasicComponent, NzTestTimelinePendingComponent, NzTestTimelineCustomColorComponent ] + imports: [NzTimelineModule], + declarations: [NzTestTimelineBasicComponent, NzTestTimelinePendingComponent, NzTestTimelineCustomColorComponent] }); TestBed.compileComponents(); })); @@ -30,26 +30,34 @@ describe('timeline', () => { it('should init className correct', () => { fixture.detectChanges(); expect(timeline.nativeElement.firstElementChild!.classList).toContain('ant-timeline'); - expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-timeline-item'))).toBe(true); - expect(items[ 0 ].nativeElement.firstElementChild!.classList).not.toContain('ant-timeline-item-last'); - expect(items[ 3 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); + expect(items.every(item => item.nativeElement.firstElementChild!.classList.contains('ant-timeline-item'))).toBe( + true + ); + expect(items[0].nativeElement.firstElementChild!.classList).not.toContain('ant-timeline-item-last'); + expect(items[3].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); }); it('should color work', () => { fixture.detectChanges(); - expect(items[ 0 ].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain('ant-timeline-item-head-blue'); + expect(items[0].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain( + 'ant-timeline-item-head-blue' + ); testComponent.color = 'red'; fixture.detectChanges(); - expect(items[ 0 ].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain('ant-timeline-item-head-red'); + expect(items[0].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain( + 'ant-timeline-item-head-red' + ); testComponent.color = 'green'; fixture.detectChanges(); - expect(items[ 0 ].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain('ant-timeline-item-head-green'); + expect(items[0].nativeElement.querySelector('.ant-timeline-item-head').classList).toContain( + 'ant-timeline-item-head-green' + ); }); it('should dot work', () => { fixture.detectChanges(); - expect(items[ 0 ].nativeElement.querySelector('.ant-timeline-item-head').innerText).toBe('dot'); - expect(items[ 1 ].nativeElement.querySelector('.ant-timeline-item-head').innerText).toBe('template'); + expect(items[0].nativeElement.querySelector('.ant-timeline-item-head').innerText).toBe('dot'); + expect(items[1].nativeElement.querySelector('.ant-timeline-item-head').innerText).toBe('template'); }); it('should last work', () => { @@ -59,7 +67,7 @@ describe('timeline', () => { fixture.detectChanges(); items = fixture.debugElement.queryAll(By.directive(NzTimelineItemComponent)); expect(items.length).toBe(5); - expect(items[ 4 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); + expect(items[4].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); }); it('should pending work', () => { @@ -77,27 +85,29 @@ describe('timeline', () => { testComponent.pending = true; testComponent.reverse = true; fixture.detectChanges(); - expect(timeline.nativeElement.firstElementChild.firstElementChild!.classList).toContain('ant-timeline-item-pending'); - expect(items[ 0 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); - expect(items[ 3 ].nativeElement.firstElementChild!.classList).not.toContain('ant-timeline-item-last'); + expect(timeline.nativeElement.firstElementChild.firstElementChild!.classList).toContain( + 'ant-timeline-item-pending' + ); + expect(items[0].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-last'); + expect(items[3].nativeElement.firstElementChild!.classList).not.toContain('ant-timeline-item-last'); }); it('should alternate position work', () => { fixture.detectChanges(); testComponent.mode = 'alternate'; fixture.detectChanges(); expect(timeline.nativeElement.firstElementChild!.classList).toContain('ant-timeline-alternate'); - expect(items[ 0 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-left'); - expect(items[ 1 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); - expect(items[ 2 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-left'); + expect(items[0].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-left'); + expect(items[1].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); + expect(items[2].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-left'); }); it('should alternate right position work', () => { fixture.detectChanges(); testComponent.mode = 'right'; fixture.detectChanges(); expect(timeline.nativeElement.firstElementChild!.classList).toContain('ant-timeline-right'); - expect(items[ 0 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); - expect(items[ 1 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); - expect(items[ 2 ].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); + expect(items[0].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); + expect(items[1].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); + expect(items[2].nativeElement.firstElementChild!.classList).toContain('ant-timeline-item-right'); }); }); describe('custom color timeline', () => { @@ -111,10 +121,12 @@ describe('timeline', () => { it('should support custom color', () => { fixture.detectChanges(); - expect(items[ 0 ].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe('grey'); - expect(items[ 1 ].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe('rgb(200, 0, 0)'); - expect(items[ 2 ].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe('rgb(120, 18, 65)'); // hex would be converted to rgb() - expect(items[ 3 ].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe(''); + expect(items[0].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe('grey'); + expect(items[1].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe('rgb(200, 0, 0)'); + expect(items[2].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe( + 'rgb(120, 18, 65)' + ); // hex would be converted to rgb() + expect(items[3].nativeElement.querySelector('.ant-timeline-item-head').style.borderColor).toBe(''); }); }); @@ -142,7 +154,8 @@ describe('timeline', () => { Technical testing 2015-09-01 Network problems being solved 2015-09-01 Network problems being solved 2015-09-01 - ` + + ` }) export class NzTestTimelineBasicComponent { color = 'blue'; @@ -161,10 +174,10 @@ export class NzTestTimelineBasicComponent { Solve initial network problems 2015-09-01 Technical testing 2015-09-01 Network problems being solved 2015-09-01 - ` + + ` }) -export class NzTestTimelineCustomColorComponent { -} +export class NzTestTimelineCustomColorComponent {} @Component({ selector: 'nz-test-timeline-pending', @@ -173,7 +186,7 @@ export class NzTestTimelineCustomColorComponent { Technical testing 2015-09-01 Network problems being solved 2015-09-01 - ` + + ` }) -export class NzTestTimelinePendingComponent { -} +export class NzTestTimelinePendingComponent {} diff --git a/components/tooltip/demo/arrow-point-at-center.ts b/components/tooltip/demo/arrow-point-at-center.ts index 50f3b67d381..d15672f5269 100644 --- a/components/tooltip/demo/arrow-point-at-center.ts +++ b/components/tooltip/demo/arrow-point-at-center.ts @@ -4,14 +4,17 @@ import { Component } from '@angular/core'; selector: 'nz-demo-tooltip-arrow-point-at-center', template: ` - + `, - styles : [ - `button { - margin-right: 8px; - margin-bottom: 8px; - }` + styles: [ + ` + button { + margin-right: 8px; + margin-bottom: 8px; + } + ` ] }) -export class NzDemoTooltipArrowPointAtCenterComponent { -} +export class NzDemoTooltipArrowPointAtCenterComponent {} diff --git a/components/tooltip/demo/basic.ts b/components/tooltip/demo/basic.ts index e49acef0664..cd71e4c9e1c 100644 --- a/components/tooltip/demo/basic.ts +++ b/components/tooltip/demo/basic.ts @@ -2,7 +2,8 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-tooltip-basic', - template: `Tooltip will show when mouse enter.` + template: ` + Tooltip will show when mouse enter. + ` }) -export class NzDemoTooltipBasicComponent { -} +export class NzDemoTooltipBasicComponent {} diff --git a/components/tooltip/demo/placement.ts b/components/tooltip/demo/placement.ts index 05e974b2deb..7fab699892f 100644 --- a/components/tooltip/demo/placement.ts +++ b/components/tooltip/demo/placement.ts @@ -24,8 +24,8 @@ import { Component } from '@angular/core';
    `, - styles : [ - ` + styles: [ + ` button { width: 70px; text-align: center; @@ -36,5 +36,4 @@ import { Component } from '@angular/core'; ` ] }) -export class NzDemoTooltipPlacementComponent { -} +export class NzDemoTooltipPlacementComponent {} diff --git a/components/tooltip/demo/template.ts b/components/tooltip/demo/template.ts index 1242e2ce48e..17d75811b0e 100644 --- a/components/tooltip/demo/template.ts +++ b/components/tooltip/demo/template.ts @@ -9,5 +9,4 @@ import { Component } from '@angular/core'; ` }) -export class NzDemoTooltipTemplateComponent { -} +export class NzDemoTooltipTemplateComponent {} diff --git a/components/tooltip/nz-tooltip.component.ts b/components/tooltip/nz-tooltip.component.ts index 0c5871ddb70..5275d018fe6 100644 --- a/components/tooltip/nz-tooltip.component.ts +++ b/components/tooltip/nz-tooltip.component.ts @@ -28,22 +28,24 @@ import { isNotNil } from '../core/util/check'; import { toBoolean } from '../core/util/convert'; @Component({ - selector : 'nz-tooltip', - changeDetection : ChangeDetectionStrategy.OnPush, - encapsulation : ViewEncapsulation.None, - animations : [ zoomBigMotion ], - templateUrl : './nz-tooltip.component.html', + selector: 'nz-tooltip', + changeDetection: ChangeDetectionStrategy.OnPush, + encapsulation: ViewEncapsulation.None, + animations: [zoomBigMotion], + templateUrl: './nz-tooltip.component.html', preserveWhitespaces: false, - styles : [ ` - .ant-tooltip { - position: relative; - } - ` ] + styles: [ + ` + .ant-tooltip { + position: relative; + } + ` + ] }) export class NzToolTipComponent implements OnChanges { _hasBackdrop = false; _prefix = 'ant-tooltip-placement'; - _positions: ConnectionPositionPair[] = [ ...DEFAULT_TOOLTIP_POSITIONS ]; + _positions: ConnectionPositionPair[] = [...DEFAULT_TOOLTIP_POSITIONS]; _classMap = {}; _placement = 'top'; _trigger = 'hover'; @@ -53,7 +55,7 @@ export class NzToolTipComponent implements OnChanges { @ViewChild('overlay') overlay: CdkConnectedOverlay; @Input() @ContentChild('nzTemplate') nzTitle: string | TemplateRef; @Input() nzOverlayClassName = ''; - @Input() nzOverlayStyle: { [ key: string ]: string } = {}; + @Input() nzOverlayStyle: { [key: string]: string } = {}; @Input() nzMouseEnterDelay = 0.15; // second @Input() nzMouseLeaveDelay = 0.1; // second @@ -84,7 +86,7 @@ export class NzToolTipComponent implements OnChanges { set nzPlacement(value: string) { if (value !== this._placement) { this._placement = value; - this._positions = [ POSITION_MAP[ this.nzPlacement ], ...this._positions ]; + this._positions = [POSITION_MAP[this.nzPlacement], ...this._positions]; } } @@ -94,10 +96,9 @@ export class NzToolTipComponent implements OnChanges { @Output() readonly nzVisibleChange = new EventEmitter(); - [ property: string ]: any // tslint:disable-line:no-any + [property: string]: any; // tslint:disable-line:no-any - constructor(public cdr: ChangeDetectorRef, @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + constructor(public cdr: ChangeDetectorRef, @Host() @Optional() public noAnimation?: NzNoAnimationDirective) {} ngOnChanges(): void { Promise.resolve().then(() => { @@ -139,8 +140,8 @@ export class NzToolTipComponent implements OnChanges { setClassMap(): void { this._classMap = { - [ this.nzOverlayClassName ] : true, - [ `${this._prefix}-${this._placement}` ]: true + [this.nzOverlayClassName]: true, + [`${this._prefix}-${this._placement}`]: true }; } @@ -149,6 +150,6 @@ export class NzToolTipComponent implements OnChanges { } protected isContentEmpty(): boolean { - return this.nzTitle instanceof TemplateRef ? false : (this.nzTitle === '' || !isNotNil(this.nzTitle)); + return this.nzTitle instanceof TemplateRef ? false : this.nzTitle === '' || !isNotNil(this.nzTitle); } } diff --git a/components/tooltip/nz-tooltip.directive.ts b/components/tooltip/nz-tooltip.directive.ts index 0d45244f716..aa857bf536c 100644 --- a/components/tooltip/nz-tooltip.directive.ts +++ b/components/tooltip/nz-tooltip.directive.ts @@ -28,7 +28,7 @@ import { NzToolTipComponent } from './nz-tooltip.component'; @Directive({ selector: '[nz-tooltip]', - host : { + host: { '[class.ant-tooltip-open]': 'isTooltipOpen' } }) @@ -67,12 +67,12 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD @Input() nzMouseEnterDelay: number; @Input() nzMouseLeaveDelay: number; @Input() nzOverlayClassName: string; - @Input() nzOverlayStyle: { [ key: string ]: string }; + @Input() nzOverlayStyle: { [key: string]: string }; @Input() nzTrigger: string; @Input() nzVisible: boolean; @Input() nzPlacement: string; - [ property: string ]: any // tslint:disable-line:no-any + [property: string]: any; // tslint:disable-line:no-any constructor( public elementRef: ElementRef, @@ -81,8 +81,7 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD public renderer: Renderer2, @Optional() public tooltip: NzToolTipComponent, @Host() @Optional() public noAnimation?: NzNoAnimationDirective - ) { - } + ) {} ngOnChanges(changes: SimpleChanges): void { this.updateProxies(changes); @@ -95,9 +94,12 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD this.tooltip = tooltipComponent.instance; this.tooltip.noAnimation = this.noAnimation; // Remove element when use directive https://github.com/NG-ZORRO/ng-zorro-antd/issues/1967 - this.renderer.removeChild(this.renderer.parentNode(this.elementRef.nativeElement), tooltipComponent.location.nativeElement); + this.renderer.removeChild( + this.renderer.parentNode(this.elementRef.nativeElement), + tooltipComponent.location.nativeElement + ); this.isDynamicTooltip = true; - this.needProxyProperties.forEach(property => this.updateCompValue(property, this[ property ])); + this.needProxyProperties.forEach(property => this.updateCompValue(property, this[property])); const visible_ = this.tooltip.nzVisibleChange.pipe(distinctUntilChanged()).subscribe(data => { this.visible = data; this.nzVisibleChange.emit(data); @@ -110,10 +112,13 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD ngAfterViewInit(): void { if (this.tooltip.nzTrigger === 'hover') { let overlayElement: HTMLElement; - this.renderer.listen(this.elementRef.nativeElement, 'mouseenter', () => this.delayEnterLeave(true, true, this.tooltip.nzMouseEnterDelay)); + this.renderer.listen(this.elementRef.nativeElement, 'mouseenter', () => + this.delayEnterLeave(true, true, this.tooltip.nzMouseEnterDelay) + ); this.renderer.listen(this.elementRef.nativeElement, 'mouseleave', () => { this.delayEnterLeave(true, false, this.tooltip.nzMouseLeaveDelay); - if (this.tooltip.overlay.overlayRef && !overlayElement) { // NOTE: we bind events under "mouseleave" due to the overlayRef is only created after the overlay was completely shown up + if (this.tooltip.overlay.overlayRef && !overlayElement) { + // NOTE: we bind events under "mouseleave" due to the overlayRef is only created after the overlay was completely shown up overlayElement = this.tooltip.overlay.overlayRef.overlayElement; this.renderer.listen(overlayElement, 'mouseenter', () => this.delayEnterLeave(false, true)); this.renderer.listen(overlayElement, 'mouseleave', () => this.delayEnterLeave(false, false)); @@ -123,7 +128,7 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD this.renderer.listen(this.elementRef.nativeElement, 'focus', () => this.show()); this.renderer.listen(this.elementRef.nativeElement, 'blur', () => this.hide()); } else if (this.tooltip.nzTrigger === 'click') { - this.renderer.listen(this.elementRef.nativeElement, 'click', (e) => { + this.renderer.listen(this.elementRef.nativeElement, 'click', e => { e.preventDefault(); this.show(); }); @@ -137,7 +142,7 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD // tslint:disable-next-line:no-any protected updateCompValue(key: string, value: any): void { if (this.isDynamicTooltip && isNotNil(value)) { - this.tooltip[ key ] = value; + this.tooltip[key] = value; } } @@ -152,7 +157,8 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD } private delayEnterLeave(isOrigin: boolean, isEnter: boolean, delay: number = -1): void { - if (this.delayTimer) { // Clear timer during the delay time + if (this.delayTimer) { + // Clear timer during the delay time clearTimeout(this.delayTimer); this.delayTimer = null; } else if (delay > 0) { @@ -172,7 +178,7 @@ export class NzTooltipDirective implements AfterViewInit, OnChanges, OnInit, OnD private updateProxies(changes: SimpleChanges): void { if (this.tooltip) { Object.keys(changes).forEach(key => { - const change = changes[ key ]; + const change = changes[key]; if (change) { this.updateCompValue(key, change.currentValue); } diff --git a/components/tooltip/nz-tooltip.module.ts b/components/tooltip/nz-tooltip.module.ts index 6eb2776f363..3ac85051d14 100644 --- a/components/tooltip/nz-tooltip.module.ts +++ b/components/tooltip/nz-tooltip.module.ts @@ -10,10 +10,9 @@ import { NzToolTipComponent } from './nz-tooltip.component'; import { NzTooltipDirective } from './nz-tooltip.directive'; @NgModule({ - declarations : [ NzToolTipComponent, NzTooltipDirective ], - exports : [ NzToolTipComponent, NzTooltipDirective ], - imports : [ CommonModule, OverlayModule, NzAddOnModule, NzOverlayModule, NzNoAnimationModule ], - entryComponents: [ NzToolTipComponent ] + declarations: [NzToolTipComponent, NzTooltipDirective], + exports: [NzToolTipComponent, NzTooltipDirective], + imports: [CommonModule, OverlayModule, NzAddOnModule, NzOverlayModule, NzNoAnimationModule], + entryComponents: [NzToolTipComponent] }) -export class NzToolTipModule { -} +export class NzToolTipModule {} diff --git a/components/tooltip/nz-tooltip.spec.ts b/components/tooltip/nz-tooltip.spec.ts index e8f39dad46c..ae55ead4581 100644 --- a/components/tooltip/nz-tooltip.spec.ts +++ b/components/tooltip/nz-tooltip.spec.ts @@ -12,15 +12,17 @@ import { NzToolTipModule } from './nz-tooltip.module'; @Component({ selector: 'nz-tooltip-test-directive', template: ` - + Show Show @@ -74,13 +76,13 @@ describe('NzTooltip', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ - imports : [ NzToolTipModule, NoopAnimationsModule, NzIconTestModule ], - declarations: [ NzTooltipTestWrapperComponent, NzTooltipTestDirectiveComponent ] + imports: [NzToolTipModule, NoopAnimationsModule, NzIconTestModule], + declarations: [NzTooltipTestWrapperComponent, NzTooltipTestDirectiveComponent] }); TestBed.compileComponents(); })); - beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { + beforeEach(inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); diff --git a/components/transfer/demo/advanced.ts b/components/transfer/demo/advanced.ts index 2417cd64e8e..9eb8f857ae4 100644 --- a/components/transfer/demo/advanced.ts +++ b/components/transfer/demo/advanced.ts @@ -8,35 +8,36 @@ import { NzMessageService } from 'ng-zorro-antd'; [nzDataSource]="list" nzShowSearch [nzOperations]="['to right', 'to left']" - [nzListStyle]="{'width.px': 250, 'height.px': 300}" + [nzListStyle]="{ 'width.px': 250, 'height.px': 300 }" [nzRender]="render" [nzFooter]="footer" (nzSelectChange)="select($event)" - (nzChange)="change($event)"> - - {{ item.title }}-{{ item.description }} - + (nzChange)="change($event)" + > + {{ item.title }}-{{ item.description }} - + ` }) export class NzDemoTransferAdvancedComponent implements OnInit { - list: Array<{ key: string, title: string, description: string, direction: string }> = []; + list: Array<{ key: string; title: string; description: string; direction: string }> = []; ngOnInit(): void { this.getData(); } getData(): void { - const ret: Array<{ key: string, title: string, description: string, direction: string }> = []; + const ret: Array<{ key: string; title: string; description: string; direction: string }> = []; for (let i = 0; i < 20; i++) { ret.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, description: `description of content${i + 1}`, - direction : Math.random() * 2 > 1 ? 'right' : '' + direction: Math.random() * 2 > 1 ? 'right' : '' }); } this.list = ret; @@ -55,6 +56,5 @@ export class NzDemoTransferAdvancedComponent implements OnInit { console.log('nzChange', ret); } - constructor(public msg: NzMessageService) { - } + constructor(public msg: NzMessageService) {} } diff --git a/components/transfer/demo/basic.ts b/components/transfer/demo/basic.ts index 0c6a30e3f82..2646f07394b 100644 --- a/components/transfer/demo/basic.ts +++ b/components/transfer/demo/basic.ts @@ -8,11 +8,13 @@ import { Component, OnInit } from '@angular/core'; [nzDisabled]="disabled" [nzTitles]="['Source', 'Target']" (nzSelectChange)="select($event)" - (nzChange)="change($event)"> + (nzChange)="change($event)" + > -
    - -
    +
    + +
    +
    ` }) export class NzDemoTransferBasicComponent implements OnInit { @@ -23,13 +25,13 @@ export class NzDemoTransferBasicComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 20; i++) { this.list.push({ - key : i.toString(), - title : `content${i + 1}`, - disabled: i % 3 < 1, + key: i.toString(), + title: `content${i + 1}`, + disabled: i % 3 < 1 }); } - [ 2, 3 ].forEach(idx => this.list[ idx ].direction = 'right'); + [2, 3].forEach(idx => (this.list[idx].direction = 'right')); } select(ret: {}): void { diff --git a/components/transfer/demo/can-move.ts b/components/transfer/demo/can-move.ts index a1ec02ddf9f..de0d70e138b 100644 --- a/components/transfer/demo/can-move.ts +++ b/components/transfer/demo/can-move.ts @@ -10,27 +10,30 @@ import { delay } from 'rxjs/operators'; [nzDataSource]="list" [nzCanMove]="canMove" (nzSelectChange)="select($event)" - (nzChange)="change($event)"> + (nzChange)="change($event)" + > ` }) export class NzDemoTransferCanMoveComponent implements OnInit { - list: Array<{ key: string, title: string, disabled: boolean, direction?: string }> = []; + list: Array<{ key: string; title: string; disabled: boolean; direction?: string }> = []; ngOnInit(): void { for (let i = 0; i < 20; i++) { this.list.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, disabled: i % 3 < 1 }); } - [ 2, 3 ].forEach(idx => this.list[ idx ].direction = 'right'); + [2, 3].forEach(idx => (this.list[idx].direction = 'right')); } canMove(arg: TransferCanMove): Observable { - if (arg.direction === 'right' && arg.list.length > 0) { arg.list.splice(0, 1); } + if (arg.direction === 'right' && arg.list.length > 0) { + arg.list.splice(0, 1); + } // or // if (arg.direction === 'right' && arg.list.length > 0) delete arg.list[0]; return of(arg.list).pipe(delay(1000)); diff --git a/components/transfer/demo/custom-item.ts b/components/transfer/demo/custom-item.ts index 9571c718de3..bdce7f2daef 100644 --- a/components/transfer/demo/custom-item.ts +++ b/components/transfer/demo/custom-item.ts @@ -6,32 +6,31 @@ import { NzMessageService } from 'ng-zorro-antd'; template: ` - - {{ item.title }} - + (nzChange)="change($event)" + > + {{ item.title }} ` }) export class NzDemoTransferCustomItemComponent implements OnInit { - list: Array<{ key: string, title: string, description: string, direction: string, icon: string }> = []; + list: Array<{ key: string; title: string; description: string; direction: string; icon: string }> = []; ngOnInit(): void { this.getData(); } getData(): void { - const ret: Array<{ key: string, title: string, description: string, direction: string, icon: string }> = []; + const ret: Array<{ key: string; title: string; description: string; direction: string; icon: string }> = []; for (let i = 0; i < 20; i++) { ret.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, description: `description of content${i + 1}`, - direction : Math.random() * 2 > 1 ? 'right' : '', - icon : `frown-o` + direction: Math.random() * 2 > 1 ? 'right' : '', + icon: `frown-o` }); } this.list = ret; @@ -45,6 +44,5 @@ export class NzDemoTransferCustomItemComponent implements OnInit { console.log('nzChange', ret); } - constructor(public msg: NzMessageService) { - } + constructor(public msg: NzMessageService) {} } diff --git a/components/transfer/demo/search.ts b/components/transfer/demo/search.ts index 5cb87da1f9e..6c3b137cbd5 100644 --- a/components/transfer/demo/search.ts +++ b/components/transfer/demo/search.ts @@ -10,11 +10,13 @@ import { Component, OnInit } from '@angular/core'; [nzFilterOption]="filterOption" (nzSearchChange)="search($event)" (nzSelectChange)="select($event)" - (nzChange)="change($event)"> + (nzChange)="change($event)" + >
    -
    +
    +
    ` }) export class NzDemoTransferSearchComponent implements OnInit { @@ -25,10 +27,10 @@ export class NzDemoTransferSearchComponent implements OnInit { ngOnInit(): void { for (let i = 0; i < 20; i++) { this.list.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, description: `description of content${i + 1}`, - direction : Math.random() * 2 > 1 ? 'right' : '' + direction: Math.random() * 2 > 1 ? 'right' : '' }); } } diff --git a/components/transfer/nz-transfer-list.component.ts b/components/transfer/nz-transfer-list.component.ts index c08206188cd..39a250e062f 100644 --- a/components/transfer/nz-transfer-list.component.ts +++ b/components/transfer/nz-transfer-list.component.ts @@ -18,12 +18,12 @@ import { NzUpdateHostClassService } from '../core/services/update-host-class.ser import { TransferItem } from './interface'; @Component({ - selector : 'nz-transfer-list', + selector: 'nz-transfer-list', preserveWhitespaces: false, - providers : [ NzUpdateHostClassService ], - templateUrl : './nz-transfer-list.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + providers: [NzUpdateHostClassService], + templateUrl: './nz-transfer-list.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzTransferListComponent implements OnChanges, OnInit { // #region fields @@ -48,7 +48,7 @@ export class NzTransferListComponent implements OnChanges, OnInit { // events @Output() readonly handleSelectAll: EventEmitter = new EventEmitter(); @Output() readonly handleSelect: EventEmitter = new EventEmitter(); - @Output() readonly filterChange: EventEmitter<{ direction: string, value: string }> = new EventEmitter(); + @Output() readonly filterChange: EventEmitter<{ direction: string; value: string }> = new EventEmitter(); // #endregion @@ -58,8 +58,8 @@ export class NzTransferListComponent implements OnChanges, OnInit { setClassMap(): void { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-with-footer` ]: !!this.footer + [this.prefixCls]: true, + [`${this.prefixCls}-with-footer`]: !!this.footer }; this.updateHostClassService.updateHostClass(this.el.nativeElement, classMap); } @@ -69,8 +69,8 @@ export class NzTransferListComponent implements OnChanges, OnInit { // #region select all stat = { - checkAll : false, - checkHalf : false, + checkAll: false, + checkHalf: false, checkCount: 0, shownCount: 0 }; @@ -120,8 +120,11 @@ export class NzTransferListComponent implements OnChanges, OnInit { // #endregion - constructor(private el: ElementRef, private updateHostClassService: NzUpdateHostClassService, private cdr: ChangeDetectorRef) { - } + constructor( + private el: ElementRef, + private updateHostClassService: NzUpdateHostClassService, + private cdr: ChangeDetectorRef + ) {} ngOnChanges(changes: SimpleChanges): void { if ('footer' in changes) { diff --git a/components/transfer/nz-transfer-search.component.ts b/components/transfer/nz-transfer-search.component.ts index c51898ae859..7f1de340fd2 100644 --- a/components/transfer/nz-transfer-search.component.ts +++ b/components/transfer/nz-transfer-search.component.ts @@ -1,14 +1,22 @@ -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, Output, ViewEncapsulation } from '@angular/core'; +import { + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + EventEmitter, + Input, + OnChanges, + Output, + ViewEncapsulation +} from '@angular/core'; @Component({ - selector : '[nz-transfer-search]', + selector: '[nz-transfer-search]', preserveWhitespaces: false, - templateUrl : './nz-transfer-search.component.html', - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + templateUrl: './nz-transfer-search.component.html', + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzTransferSearchComponent implements OnChanges { - // region: fields @Input() placeholder: string; @@ -28,7 +36,7 @@ export class NzTransferSearchComponent implements OnChanges { _clear(): void { if (this.disabled) { - return ; + return; } this.value = ''; this.valueClear.emit(); @@ -37,5 +45,4 @@ export class NzTransferSearchComponent implements OnChanges { ngOnChanges(): void { this.cdr.detectChanges(); } - } diff --git a/components/transfer/nz-transfer.component.ts b/components/transfer/nz-transfer.component.ts index 7e5f956c25f..75e00166146 100644 --- a/components/transfer/nz-transfer.component.ts +++ b/components/transfer/nz-transfer.component.ts @@ -1,14 +1,16 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, - Component, ElementRef, + Component, + ElementRef, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, - QueryList, Renderer2, + QueryList, + Renderer2, SimpleChanges, TemplateRef, ViewChildren, @@ -25,19 +27,19 @@ import { TransferCanMove, TransferChange, TransferItem, TransferSearchChange, Tr import { NzTransferListComponent } from './nz-transfer-list.component'; @Component({ - selector : 'nz-transfer', + selector: 'nz-transfer', preserveWhitespaces: false, - templateUrl : './nz-transfer.component.html', - host : { + templateUrl: './nz-transfer.component.html', + host: { '[class.ant-transfer-disabled]': 'nzDisabled' }, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { private unsubscribe$ = new Subject(); @ViewChildren(NzTransferListComponent) - private lists !: QueryList; + private lists!: QueryList; // tslint:disable-next-line:no-any locale: any = {}; @@ -48,7 +50,7 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { @Input() @InputBoolean() nzDisabled = false; @Input() nzDataSource: TransferItem[] = []; - @Input() nzTitles: string[] = [ '', '' ]; + @Input() nzTitles: string[] = ['', '']; @Input() nzOperations: string[] = []; @Input() nzListStyle: object; @Input() nzItemUnit: string; @@ -89,7 +91,7 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { } private getCheckedData(direction: string): TransferItem[] { - return this[ direction === 'left' ? 'leftDataSource' : 'rightDataSource' ].filter(w => w.checked); + return this[direction === 'left' ? 'leftDataSource' : 'rightDataSource'].filter(w => w.checked); } handleLeftSelectAll = (checked: boolean) => this.handleSelect('left', checked); @@ -104,7 +106,7 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { this.nzSelectChange.emit({ direction, checked, list, item }); } - handleFilterChange(ret: { direction: string, value: string }): void { + handleFilterChange(ret: { direction: string; value: string }): void { this.nzSearchChange.emit(ret); } @@ -116,7 +118,8 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { rightActive = false; private updateOperationStatus(direction: string, count?: number): void { - this[ direction === 'right' ? 'leftActive' : 'rightActive' ] = (typeof count === 'undefined' ? this.getCheckedData(direction).filter(w => !w.disabled).length : count) > 0; + this[direction === 'right' ? 'leftActive' : 'rightActive'] = + (typeof count === 'undefined' ? this.getCheckedData(direction).filter(w => !w.disabled).length : count) > 0; } moveToLeft = () => this.moveTo('left'); @@ -127,10 +130,9 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { this.updateOperationStatus(oppositeDirection, 0); const datasource = direction === 'left' ? this.rightDataSource : this.leftDataSource; const moveList = datasource.filter(item => item.checked === true && !item.disabled); - this.nzCanMove({ direction, list: moveList }) - .subscribe( + this.nzCanMove({ direction, list: moveList }).subscribe( newMoveList => this.truthMoveTo(direction, newMoveList.filter(i => !!i)), - () => moveList.forEach(i => i.checked = false) + () => moveList.forEach(i => (i.checked = false)) ); } @@ -146,7 +148,7 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { this.updateOperationStatus(oppositeDirection); this.nzChange.emit({ from: oppositeDirection, - to : direction, + to: direction, list }); this.markForCheckAllList(); @@ -154,7 +156,12 @@ export class NzTransferComponent implements OnInit, OnChanges, OnDestroy { // #endregion - constructor(private cdr: ChangeDetectorRef, private i18n: NzI18nService, renderer: Renderer2, elementRef: ElementRef) { + constructor( + private cdr: ChangeDetectorRef, + private i18n: NzI18nService, + renderer: Renderer2, + elementRef: ElementRef + ) { renderer.addClass(elementRef.nativeElement, 'ant-transfer'); } diff --git a/components/transfer/nz-transfer.module.ts b/components/transfer/nz-transfer.module.ts index 2b6c6ee88ad..7314d176431 100644 --- a/components/transfer/nz-transfer.module.ts +++ b/components/transfer/nz-transfer.module.ts @@ -14,9 +14,17 @@ import { NzTransferSearchComponent } from './nz-transfer-search.component'; import { NzTransferComponent } from './nz-transfer.component'; @NgModule({ - imports : [ CommonModule, FormsModule, NzCheckboxModule, NzButtonModule, NzInputModule, NzI18nModule, NzIconModule, NzEmptyModule ], - declarations: [ NzTransferComponent, NzTransferListComponent, NzTransferSearchComponent ], - exports : [ NzTransferComponent ] + imports: [ + CommonModule, + FormsModule, + NzCheckboxModule, + NzButtonModule, + NzInputModule, + NzI18nModule, + NzIconModule, + NzEmptyModule + ], + declarations: [NzTransferComponent, NzTransferListComponent, NzTransferSearchComponent], + exports: [NzTransferComponent] }) -export class NzTransferModule { -} +export class NzTransferModule {} diff --git a/components/transfer/transfer.spec.ts b/components/transfer/transfer.spec.ts index 0b7c75115e0..f3df44bbd3e 100644 --- a/components/transfer/transfer.spec.ts +++ b/components/transfer/transfer.spec.ts @@ -24,8 +24,8 @@ describe('transfer', () => { let pageObject: TransferPageObject; beforeEach(() => { injector = TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, NzTransferModule, NzIconTestModule ], - declarations: [ TestTransferComponent, TestTransferCustomRenderComponent, Test996Component ] + imports: [NoopAnimationsModule, NzTransferModule, NzIconTestModule], + declarations: [TestTransferComponent, TestTransferCustomRenderComponent, Test996Component] }); fixture = TestBed.createComponent(TestTransferComponent); dl = fixture.debugElement; @@ -36,21 +36,24 @@ describe('transfer', () => { describe('[default]', () => { it('should be from left to right', () => { - pageObject.expectLeft(LEFTCOUNT) + pageObject + .expectLeft(LEFTCOUNT) .transfer('right', 0) .expectLeft(LEFTCOUNT - 1) .expectRight(COUNT - LEFTCOUNT + 1); }); it('should be from right to left', () => { - pageObject.expectRight(COUNT - LEFTCOUNT) - .transfer('left', [ 0, 1 ]) + pageObject + .expectRight(COUNT - LEFTCOUNT) + .transfer('left', [0, 1]) .expectRight(COUNT - LEFTCOUNT - 2) .expectLeft(LEFTCOUNT + 2); }); it('should be from left to right when via search found items', () => { - pageObject.expectLeft(LEFTCOUNT) + pageObject + .expectLeft(LEFTCOUNT) .search('left', '1') .transfer('right', 0) .expectLeft(LEFTCOUNT - 1) @@ -59,9 +62,10 @@ describe('transfer', () => { }); it('should be from right to left when via search found items', () => { - pageObject.expectRight(COUNT - LEFTCOUNT) + pageObject + .expectRight(COUNT - LEFTCOUNT) .search('right', '2') - .transfer('left', [ 0, 1 ]) + .transfer('left', [0, 1]) .expectLeft(LEFTCOUNT + 2) .expectRight(COUNT - LEFTCOUNT - 2); expect(pageObject.rightList.querySelectorAll('.ant-transfer-list-content-item').length).toBe(DISABLED); @@ -96,7 +100,7 @@ describe('transfer', () => { }); it('should be checkbox is disabled toggle select when setting disabled prop', () => { - instance.nzDataSource = [ { title: `content`, disabled: true } ]; + instance.nzDataSource = [{ title: `content`, disabled: true }]; fixture.detectChanges(); expect(instance.comp.leftDataSource.filter(w => w.checked).length).toBe(0); pageObject.checkItem('left', 0); @@ -107,7 +111,7 @@ describe('transfer', () => { it('should be checkbox is toggle select via checkbox all in left', () => { expect(instance.comp.leftDataSource.filter(w => w.checked).length).toBe(0); - const btn = (pageObject.leftList.querySelector('.ant-transfer-list-header .ant-checkbox') as HTMLElement); + const btn = pageObject.leftList.querySelector('.ant-transfer-list-header .ant-checkbox') as HTMLElement; btn.click(); expect(instance.comp.leftDataSource.filter(w => w.checked).length).toBe(LEFTCOUNT); btn.click(); @@ -116,7 +120,7 @@ describe('transfer', () => { it('should be checkbox is toggle select via checkbox all in right', () => { expect(instance.comp.rightDataSource.filter(w => w.checked).length).toBe(0); - const btn = (pageObject.rightList.querySelector('.ant-transfer-list-header .ant-checkbox') as HTMLElement); + const btn = pageObject.rightList.querySelector('.ant-transfer-list-header .ant-checkbox') as HTMLElement; btn.click(); expect(instance.comp.rightDataSource.filter(w => w.checked).length).toBe(COUNT - LEFTCOUNT - DISABLED); btn.click(); @@ -125,19 +129,19 @@ describe('transfer', () => { describe('#notFoundContent', () => { it('should be the left and right list have data', () => { - instance.nzDataSource = [ { title: `content0`, direction: 'right' }, { title: `content1` } ]; + instance.nzDataSource = [{ title: `content0`, direction: 'right' }, { title: `content1` }]; fixture.detectChanges(); expect(pageObject.rightList.querySelector('.ant-transfer-list-body-not-found')).toBeFalsy(); expect(pageObject.leftList.querySelector('.ant-transfer-list-body-not-found')).toBeFalsy(); }); it('should be the right list is no data', () => { - instance.nzDataSource = [ { title: `content0` }, { title: `content1` } ]; + instance.nzDataSource = [{ title: `content0` }, { title: `content1` }]; fixture.detectChanges(); expect(pageObject.rightList.querySelector('.ant-transfer-list-body-not-found')).toBeTruthy(); expect(pageObject.leftList.querySelector('.ant-transfer-list-body-not-found')).toBeFalsy(); }); it('should be the left list is no data', () => { - instance.nzDataSource = [ { title: `content0`, direction: 'right' } ]; + instance.nzDataSource = [{ title: `content0`, direction: 'right' }]; fixture.detectChanges(); expect(pageObject.rightList.querySelector('.ant-transfer-list-body-not-found')).toBeFalsy(); expect(pageObject.leftList.querySelector('.ant-transfer-list-body-not-found')).toBeTruthy(); @@ -182,13 +186,16 @@ describe('transfer', () => { it('should be uncheck all when two verification error', () => { instance.canMove = (arg: TransferCanMove): Observable => { - return of(arg.list).pipe(map(() => { - throw new Error('error'); - })); + return of(arg.list).pipe( + map(() => { + throw new Error('error'); + }) + ); }; fixture.detectChanges(); - pageObject.expectLeft(LEFTCOUNT) - .transfer('right', [ 0, 1 ]) + pageObject + .expectLeft(LEFTCOUNT) + .transfer('right', [0, 1]) .expectLeft(LEFTCOUNT) .expectRight(COUNT - LEFTCOUNT); }); @@ -209,7 +216,8 @@ describe('transfer', () => { tempFixture.detectChanges(); injector.get(NzI18nService).setLocale(en_US); tempFixture.detectChanges(); - const searchPhText = (tempFixture.debugElement.query(By.css('.ant-transfer-list-search')).nativeElement as HTMLElement).attributes.getNamedItem('placeholder')!.textContent; + const searchPhText = (tempFixture.debugElement.query(By.css('.ant-transfer-list-search')) + .nativeElement as HTMLElement).attributes.getNamedItem('placeholder')!.textContent; expect(searchPhText).toBe(en_US.Transfer.searchPlaceholder); }); }); @@ -221,7 +229,8 @@ describe('transfer', () => { instance = dl.componentInstance; pageObject = new TransferPageObject(); fixture.detectChanges(); - pageObject.expectLeft(LEFTCOUNT) + pageObject + .expectLeft(LEFTCOUNT) .transfer('right', 0) .expectLeft(LEFTCOUNT - 1) .expectRight(COUNT - LEFTCOUNT + 1); @@ -234,8 +243,9 @@ describe('transfer', () => { return of(arg.list); }; fixture.detectChanges(); - pageObject.expectLeft(LEFTCOUNT) - .transfer('right', [ 0, 1 ]) + pageObject + .expectLeft(LEFTCOUNT) + .transfer('right', [0, 1]) .expectLeft(LEFTCOUNT - 1) .expectRight(COUNT - LEFTCOUNT + 1); }); @@ -248,16 +258,20 @@ describe('transfer', () => { instance = dl.componentInstance; pageObject = new TransferPageObject(); fixture.detectChanges(); - expect(pageObject.getEl('[data-direction="right"] .ant-transfer-list-header .ant-checkbox').classList).not.toContain('ant-checkbox-checked'); + expect( + pageObject.getEl('[data-direction="right"] .ant-transfer-list-header .ant-checkbox').classList + ).not.toContain('ant-checkbox-checked'); pageObject.checkItem('right', 1); tick(50); fixture.detectChanges(); - expect(pageObject.getEl('[data-direction="right"] .ant-transfer-list-header .ant-checkbox').classList).toContain('ant-checkbox-checked'); + expect(pageObject.getEl('[data-direction="right"] .ant-transfer-list-header .ant-checkbox').classList).toContain( + 'ant-checkbox-checked' + ); })); }); class TransferPageObject { - [ key: string ]: any; + [key: string]: any; getEl(cls: string): HTMLElement { return dl.query(By.css(cls)).nativeElement as HTMLElement; @@ -281,7 +295,7 @@ describe('transfer', () => { transfer(direction: 'left' | 'right', index: number | number[]): this { if (!Array.isArray(index)) { - index = [ index ]; + index = [index]; } this.checkItem(direction === 'left' ? 'right' : 'left', index); (direction === 'left' ? this.leftBtn : this.rightBtn).click(); @@ -291,11 +305,13 @@ describe('transfer', () => { checkItem(direction: 'left' | 'right', index: number | number[]): this { if (!Array.isArray(index)) { - index = [ index ]; + index = [index]; } - const items = (direction === 'left' ? this.leftList : this.rightList).querySelectorAll('.ant-transfer-list-content-item label'); + const items = (direction === 'left' ? this.leftList : this.rightList).querySelectorAll( + '.ant-transfer-list-content-item label' + ); for (const idx of index) { - (items[ idx ] as HTMLElement).click(); + (items[idx] as HTMLElement).click(); fixture.detectChanges(); } fixture.detectChanges(); @@ -303,7 +319,9 @@ describe('transfer', () => { } search(direction: 'left' | 'right', value: string): this { - const ipt = ((direction === 'left' ? this.leftList : this.rightList).querySelector('.ant-transfer-list-search') as HTMLInputElement); + const ipt = (direction === 'left' ? this.leftList : this.rightList).querySelector( + '.ant-transfer-list-search' + ) as HTMLInputElement; ipt.value = value; ipt.dispatchEvent(new Event('input')); fixture.detectChanges(); @@ -323,38 +341,40 @@ describe('transfer', () => { }); @Component({ - template : ` - + template: ` + `, - styleUrls : [ './style/index.less' ], + styleUrls: ['./style/index.less'], encapsulation: ViewEncapsulation.None }) class TestTransferComponent implements OnInit { @ViewChild('comp') comp: NzTransferComponent; nzDataSource: any[] = []; nzDisabled = false; - nzTitles = [ 'Source', 'Target' ]; - nzOperations = [ 'to right', 'to left' ]; + nzTitles = ['Source', 'Target']; + nzOperations = ['to right', 'to left']; nzItemUnit = 'item'; nzItemsUnit = 'items'; nzListStyle = { 'width.px': 300, 'height.px': 300 }; @@ -371,55 +391,54 @@ class TestTransferComponent implements OnInit { } ngOnInit(): void { - const ret: Array<{ key: string, title: string, description: string, direction: string, icon: string, disabled: boolean }> = []; + const ret: Array<{ + key: string; + title: string; + description: string; + direction: string; + icon: string; + disabled: boolean; + }> = []; for (let i = 0; i < COUNT; i++) { ret.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, description: `description of content${i + 1}`, - direction : i >= LEFTCOUNT ? 'right' : '', - icon : `frown-o`, - disabled : i === 20 + direction: i >= LEFTCOUNT ? 'right' : '', + icon: `frown-o`, + disabled: i === 20 }); } this.nzDataSource = ret; } - search(): void { - } + search(): void {} - select(): void { - } + select(): void {} - change(): void { - } + change(): void {} } @Component({ template: ` - - - {{ item.title }} - + + {{ item.title }} ` }) class TestTransferCustomRenderComponent implements OnInit { @ViewChild('comp') comp: NzTransferComponent; - nzDataSource: Array<{ key: string, title: string, description: string, direction: string, icon: string }> = []; + nzDataSource: Array<{ key: string; title: string; description: string; direction: string; icon: string }> = []; ngOnInit(): void { - const ret: Array<{ key: string, title: string, description: string, direction: string, icon: string }> = []; + const ret: Array<{ key: string; title: string; description: string; direction: string; icon: string }> = []; for (let i = 0; i < COUNT; i++) { ret.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, description: `description of content${i + 1}`, - direction : i >= LEFTCOUNT ? 'right' : '', - icon : `frown-o` + direction: i >= LEFTCOUNT ? 'right' : '', + icon: `frown-o` }); } this.nzDataSource = ret; @@ -428,7 +447,8 @@ class TestTransferCustomRenderComponent implements OnInit { @Component({ template: ` - ` + + ` }) class Test996Component implements OnInit { // tslint:disable-next-line:no-any @@ -437,12 +457,12 @@ class Test996Component implements OnInit { ngOnInit(): void { for (let i = 0; i < 2; i++) { this.list.push({ - key : i.toString(), - title : `content${i + 1}`, + key: i.toString(), + title: `content${i + 1}`, disabled: i % 3 < 1 }); } - [ 0, 1 ].forEach(idx => this.list[ idx ].direction = 'right'); + [0, 1].forEach(idx => (this.list[idx].direction = 'right')); } } diff --git a/components/tree-select/demo/async.ts b/components/tree-select/demo/async.ts index abdf53a5466..b54d0522db0 100755 --- a/components/tree-select/demo/async.ts +++ b/components/tree-select/demo/async.ts @@ -4,7 +4,8 @@ import { NzFormatEmitEvent } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-tree-select-async', template: ` - + (nzExpandChange)="onExpandChange($event)" + > ` }) - export class NzDemoTreeSelectAsyncComponent implements OnInit { - expandKeys = [ '0-0' ]; + expandKeys = ['0-0']; value: string; - nodes = [ { - title : 'Node1', - value : '0-0', - key : '0-0', - children: [ { - title: 'Child Node1', - value: '0-0-1', - key : '0-0-1' - }, { - title: 'Child Node2', - value: '0-0-2', - key : '0-0-2' - } ] - }, { - title: 'Node2', - value: '0-1', - key : '0-1' - } ]; + nodes = [ + { + title: 'Node1', + value: '0-0', + key: '0-0', + children: [ + { + title: 'Child Node1', + value: '0-0-1', + key: '0-0-1' + }, + { + title: 'Child Node2', + value: '0-0-2', + key: '0-0-2' + } + ] + }, + { + title: 'Node2', + value: '0-1', + key: '0-1' + } + ]; onExpandChange(e: Required): void { if (e.node.getChildren().length === 0 && e.node.isExpanded) { @@ -49,13 +56,16 @@ export class NzDemoTreeSelectAsyncComponent implements OnInit { loadNode(): Promise { return new Promise(resolve => { - setTimeout(() => resolve([ - { title: 'Child Node', key: `${(new Date()).getTime()}-0` }, - { title: 'Child Node', key: `${(new Date()).getTime()}-1` } ]), - 1000); + setTimeout( + () => + resolve([ + { title: 'Child Node', key: `${new Date().getTime()}-0` }, + { title: 'Child Node', key: `${new Date().getTime()}-1` } + ]), + 1000 + ); }); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree-select/demo/basic.ts b/components/tree-select/demo/basic.ts index 80afd6d2c38..c0f522c3be9 100755 --- a/components/tree-select/demo/basic.ts +++ b/components/tree-select/demo/basic.ts @@ -10,31 +10,35 @@ import { Component, OnInit } from '@angular/core'; nzShowSearch nzPlaceHolder="Please select" [(ngModel)]="value" - (ngModelChange)="onChange($event)"> - ` + (ngModelChange)="onChange($event)" + > + + ` }) - export class NzDemoTreeSelectBasicComponent implements OnInit { - expandKeys = [ '100', '1001' ]; + expandKeys = ['100', '1001']; value: string; - nodes = [ { - title : 'parent 1', - key : '100', - children: [ { - title : 'parent 1-0', - key : '1001', - children: [ - { title: 'leaf 1-0-0', key: '10010', isLeaf: true }, - { title: 'leaf 1-0-1', key: '10011', isLeaf: true } - ] - }, { - title : 'parent 1-1', - key : '1002', + nodes = [ + { + title: 'parent 1', + key: '100', children: [ - { title: 'leaf 1-1-0', key: '10020', isLeaf: true } + { + title: 'parent 1-0', + key: '1001', + children: [ + { title: 'leaf 1-0-0', key: '10010', isLeaf: true }, + { title: 'leaf 1-0-1', key: '10011', isLeaf: true } + ] + }, + { + title: 'parent 1-1', + key: '1002', + children: [{ title: 'leaf 1-1-0', key: '10020', isLeaf: true }] + } ] - } ] - } ]; + } + ]; onChange($event: string): void { console.log($event); diff --git a/components/tree-select/demo/checkable.ts b/components/tree-select/demo/checkable.ts index 2abd210c879..9f0b699a207 100755 --- a/components/tree-select/demo/checkable.ts +++ b/components/tree-select/demo/checkable.ts @@ -10,49 +10,57 @@ import { Component, OnInit } from '@angular/core'; nzCheckable nzPlaceHolder="Please select" [(ngModel)]="value" - (ngModelChange)="onChange($event)"> - ` + (ngModelChange)="onChange($event)" + > + + ` }) - export class NzDemoTreeSelectCheckableComponent implements OnInit { - - value: string[] = [ '0-0-0' ]; - nodes = [ { - title : 'Node1', - value : '0-0', - key : '0-0', - children: [ { - title : 'Child Node1', - value : '0-0-0', - key : '0-0-0', - isLeaf: true - } ] - }, { - title : 'Node2', - value : '0-1', - key : '0-1', - children: [ { - title : 'Child Node3', - value : '0-1-0', - key : '0-1-0', - isLeaf: true - }, { - title : 'Child Node4', - value : '0-1-1', - key : '0-1-1', - isLeaf: true - }, { - title : 'Child Node5', - value : '0-1-2', - key : '0-1-2', - isLeaf: true - } ] - } ]; + value: string[] = ['0-0-0']; + nodes = [ + { + title: 'Node1', + value: '0-0', + key: '0-0', + children: [ + { + title: 'Child Node1', + value: '0-0-0', + key: '0-0-0', + isLeaf: true + } + ] + }, + { + title: 'Node2', + value: '0-1', + key: '0-1', + children: [ + { + title: 'Child Node3', + value: '0-1-0', + key: '0-1-0', + isLeaf: true + }, + { + title: 'Child Node4', + value: '0-1-1', + key: '0-1-1', + isLeaf: true + }, + { + title: 'Child Node5', + value: '0-1-2', + key: '0-1-2', + isLeaf: true + } + ] + } + ]; onChange($event: string[]): void { console.log($event); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree-select/demo/multiple.ts b/components/tree-select/demo/multiple.ts index 9582a31552f..51ad70f835e 100755 --- a/components/tree-select/demo/multiple.ts +++ b/components/tree-select/demo/multiple.ts @@ -3,7 +3,8 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-tree-select-multiple', template: ` - + (ngModelChange)="onChange($event)" + > - - and {{omittedValues.length}} more... - + and {{ omittedValues.length }} more... ` }) - export class NzDemoTreeSelectMultipleComponent implements OnInit { - value: string[] = []; - nodes = [ { - title : 'parent 1', - key : '100', - children: [ { - title : 'parent 1-0', - key : '1001', + nodes = [ + { + title: 'parent 1', + key: '100', children: [ - { title: 'leaf 1-0-0', key: '10010', isLeaf: true }, - { title: 'leaf 1-0-1', key: '10011', isLeaf: true } + { + title: 'parent 1-0', + key: '1001', + children: [ + { title: 'leaf 1-0-0', key: '10010', isLeaf: true }, + { title: 'leaf 1-0-1', key: '10011', isLeaf: true } + ] + }, + { + title: 'parent 1-1', + key: '1002', + children: [{ title: 'leaf 1-1-0', key: '10020', isLeaf: true }] + } ] - }, { - title : 'parent 1-1', - key : '1002', - children: [ - { title: 'leaf 1-1-0', key: '10020', isLeaf: true } - ] - } ] - } ]; + } + ]; onChange($event: string[]): void { console.log($event); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree-select/nz-tree-select.component.ts b/components/tree-select/nz-tree-select.component.ts index e0527665a06..08e1a0e2b19 100644 --- a/components/tree-select/nz-tree-select.component.ts +++ b/components/tree-select/nz-tree-select.component.ts @@ -1,9 +1,5 @@ import { BACKSPACE } from '@angular/cdk/keycodes'; -import { - CdkConnectedOverlay, - CdkOverlayOrigin, - ConnectedOverlayPositionChange -} from '@angular/cdk/overlay'; +import { CdkConnectedOverlay, CdkOverlayOrigin, ConnectedOverlayPositionChange } from '@angular/cdk/overlay'; import { forwardRef, ChangeDetectorRef, @@ -24,11 +20,7 @@ import { } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; -import { - merge, - of as observableOf, - Subscription -} from 'rxjs'; +import { merge, of as observableOf, Subscription } from 'rxjs'; import { filter, tap } from 'rxjs/operators'; import { slideMotion } from '../core/animation/slide'; @@ -42,40 +34,41 @@ import { NzTreeComponent } from '../tree/nz-tree.component'; import { NzTreeSelectService } from './nz-tree-select.service'; @Component({ - selector : 'nz-tree-select', - animations : [ slideMotion, zoomMotion ], + selector: 'nz-tree-select', + animations: [slideMotion, zoomMotion], templateUrl: './nz-tree-select.component.html', - providers : [ + providers: [ NzTreeSelectService, { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzTreeSelectComponent), - multi : true + multi: true } ], - host : { - '[class.ant-select-lg]' : 'nzSize==="large"', - '[class.ant-select-sm]' : 'nzSize==="small"', - '[class.ant-select-enabled]' : '!nzDisabled', - '[class.ant-select-disabled]' : 'nzDisabled', + host: { + '[class.ant-select-lg]': 'nzSize==="large"', + '[class.ant-select-sm]': 'nzSize==="small"', + '[class.ant-select-enabled]': '!nzDisabled', + '[class.ant-select-disabled]': 'nzDisabled', '[class.ant-select-allow-clear]': 'nzAllowClear', - '[class.ant-select-open]' : 'nzOpen', - '(click)' : 'trigger()' + '[class.ant-select-open]': 'nzOpen', + '(click)': 'trigger()' }, - styles : [ ` - .ant-select-dropdown { - top: 100%; - left: 0; - position: relative; - width: 100%; - margin-top: 4px; - margin-bottom: 4px; - overflow: auto; - } - ` ] + styles: [ + ` + .ant-select-dropdown { + top: 100%; + left: 0; + position: relative; + width: 100%; + margin-top: 4px; + margin-bottom: 4px; + overflow: auto; + } + ` + ] }) export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDestroy, OnChanges { - @Input() @InputBoolean() nzAllowClear = true; @Input() @InputBoolean() nzShowExpand = true; @Input() @InputBoolean() nzDropdownMatchSelectWidth = true; @@ -91,7 +84,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe @Input() nzOpen = false; @Input() nzSize: NzSizeLDSType = 'default'; @Input() nzPlaceHolder = ''; - @Input() nzDropdownStyle: { [ key: string ]: string; }; + @Input() nzDropdownStyle: { [key: string]: string }; @Input() nzDefaultExpandedKeys: string[] = []; @Input() nzDisplayWith: (node: NzTreeNode) => string | undefined = (node: NzTreeNode) => node.title; @Input() nzMaxTagCount: number; @@ -133,7 +126,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe return this.nzMultiple || this.nzCheckable; } - get selectedValueDisplay(): { [ key: string ]: string } { + get selectedValueDisplay(): { [key: string]: string } { let showSelectedValue = false; let opacity = 1; if (!this.nzShowSearch) { @@ -159,7 +152,8 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe private cdr: ChangeDetectorRef, private nzTreeService: NzTreeSelectService, private elementRef: ElementRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) { this.renderer.addClass(this.elementRef.nativeElement, 'ant-select'); } @@ -190,7 +184,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe if (this.isMultiple && Array.isArray(value)) { this.value = value; } else { - this.value = [ (value as string) ]; + this.value = [value as string]; } this.updateSelectedNodes(true); } else { @@ -241,18 +235,14 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe onKeyDownInput(e: KeyboardEvent): void { const keyCode = e.keyCode; const eventTarget = e.target as HTMLInputElement; - if ( - this.isMultiple && - !eventTarget.value && - keyCode === BACKSPACE - ) { + if (this.isMultiple && !eventTarget.value && keyCode === BACKSPACE) { e.preventDefault(); if (this.selectedNodes.length) { - const removeNode = this.selectedNodes[ this.selectedNodes.length - 1 ]; + const removeNode = this.selectedNodes[this.selectedNodes.length - 1]; this.removeSelected(removeNode); this.nzTreeService!.triggerEventChange$!.next({ - 'eventName': 'removeSelect', - 'node' : removeNode + eventName: 'removeSelect', + node: removeNode }); } } @@ -260,7 +250,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe onExpandedKeysChange(value: NzFormatEmitEvent): void { this.nzExpandChange.emit(value); - this.nzDefaultExpandedKeys = [ ...value.keys! ]; + this.nzDefaultExpandedKeys = [...value.keys!]; } setInputValue(value: string): void { @@ -311,7 +301,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe }), filter((event: NzFormatEmitEvent) => { const node = event.node!; - return this.nzCheckable ? (!node.isDisabled && !node.isDisableCheckbox) : !node.isDisabled; + return this.nzCheckable ? !node.isDisabled && !node.isDisableCheckbox : !node.isDisabled; }) ), this.nzCheckable ? this.nzTreeCheckBoxChange : observableOf(), @@ -320,7 +310,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe ).subscribe(() => { this.updateSelectedNodes(); const value = this.selectedNodes.map(node => node.key!); - this.value = [ ...value ]; + this.value = [...value]; if (this.nzShowSearch || this.isMultiple) { this.inputValue = ''; this.isNotFound = false; @@ -331,7 +321,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe this.updatePosition(); } else { this.closeDropDown(); - this.onChange(value.length ? value[ 0 ] : null); + this.onChange(value.length ? value[0] : null); } }); } @@ -342,9 +332,9 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe this.nzTreeService.isMultiple = this.isMultiple; if (!this.nzTreeService.isArrayOfNzTreeNode(this.nzNodes)) { // has not been new NzTreeNode - nodes = this.nzNodes.map(item => (new NzTreeNode(item, undefined, this.nzTreeService))); + nodes = this.nzNodes.map(item => new NzTreeNode(item, undefined, this.nzTreeService)); } else { - nodes = this.nzNodes.map(item => (new NzTreeNode({ ...item.origin }, undefined, this.nzTreeService))); + nodes = this.nzNodes.map(item => new NzTreeNode({ ...item.origin }, undefined, this.nzTreeService)); } this.nzTreeService.initTree(nodes); if (this.nzCheckable) { @@ -353,7 +343,9 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe this.nzTreeService.calcSelectedKeys(this.value, nodes, this.isMultiple); } } - this.selectedNodes = [ ...(this.nzCheckable ? this.nzTreeService.getCheckedNodeList() : this.nzTreeService.getSelectedNodeList()) ]; + this.selectedNodes = [ + ...(this.nzCheckable ? this.nzTreeService.getCheckedNodeList() : this.nzTreeService.getSelectedNodeList()) + ]; } updatePosition(): void { @@ -371,7 +363,11 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe updateInputWidth(): void { if (this.isMultiple && this.inputElement) { if (this.inputValue || this.isComposing) { - this.renderer.setStyle(this.inputElement.nativeElement, 'width', `${this.inputElement.nativeElement.scrollWidth}px`); + this.renderer.setStyle( + this.inputElement.nativeElement, + 'width', + `${this.inputElement.nativeElement.scrollWidth}px` + ); } else { this.renderer.removeStyle(this.inputElement.nativeElement, 'width'); } @@ -389,9 +385,7 @@ export class NzTreeSelectComponent implements ControlValueAccessor, OnInit, OnDe setSearchValues($event: NzFormatEmitEvent): void { Promise.resolve().then(() => { - this.isNotFound = (this.nzShowSearch || this.isMultiple) - && !!this.inputValue - && $event.matchedKeys!.length === 0; + this.isNotFound = (this.nzShowSearch || this.isMultiple) && !!this.inputValue && $event.matchedKeys!.length === 0; }); } diff --git a/components/tree-select/nz-tree-select.module.ts b/components/tree-select/nz-tree-select.module.ts index 3d8b0f0b210..96f22617c6e 100644 --- a/components/tree-select/nz-tree-select.module.ts +++ b/components/tree-select/nz-tree-select.module.ts @@ -10,9 +10,17 @@ import { NzTreeModule } from '../tree/nz-tree.module'; import { NzTreeSelectComponent } from './nz-tree-select.component'; @NgModule({ - imports : [ CommonModule, OverlayModule, FormsModule, NzTreeModule, NzIconModule, NzEmptyModule, NzOverlayModule, NzNoAnimationModule ], - declarations: [ NzTreeSelectComponent ], - exports : [ NzTreeSelectComponent ] + imports: [ + CommonModule, + OverlayModule, + FormsModule, + NzTreeModule, + NzIconModule, + NzEmptyModule, + NzOverlayModule, + NzNoAnimationModule + ], + declarations: [NzTreeSelectComponent], + exports: [NzTreeSelectComponent] }) -export class NzTreeSelectModule { -} +export class NzTreeSelectModule {} diff --git a/components/tree-select/nz-tree-select.service.ts b/components/tree-select/nz-tree-select.service.ts index 6f02824f5d5..772d7e76b64 100644 --- a/components/tree-select/nz-tree-select.service.ts +++ b/components/tree-select/nz-tree-select.service.ts @@ -2,6 +2,4 @@ import { Injectable } from '@angular/core'; import { NzTreeBaseService } from '../tree/nz-tree-base.service'; @Injectable() -export class NzTreeSelectService extends NzTreeBaseService { - -} +export class NzTreeSelectService extends NzTreeBaseService {} diff --git a/components/tree-select/nz-tree-select.spec.ts b/components/tree-select/nz-tree-select.spec.ts index c00889782c8..89de0404913 100644 --- a/components/tree-select/nz-tree-select.spec.ts +++ b/components/tree-select/nz-tree-select.spec.ts @@ -16,17 +16,17 @@ describe('tree-select component', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzTreeSelectModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestTreeSelectBasicComponent, NzTestTreeSelectCheckableComponent, NzTestTreeSelectFormComponent ] + imports: [NzTreeSelectModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule], + declarations: [NzTestTreeSelectBasicComponent, NzTestTreeSelectCheckableComponent, NzTestTreeSelectFormComponent] }); TestBed.compileComponents(); - inject([ OverlayContainer ], (oc: OverlayContainer) => { + inject([OverlayContainer], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })(); })); - afterEach(inject([ OverlayContainer ], (currentOverlayContainer: OverlayContainer) => { + afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => { currentOverlayContainer.ngOnDestroy(); overlayContainer.ngOnDestroy(); })); @@ -72,7 +72,7 @@ describe('tree-select component', () => { fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(false); }); - it('should close when the outside clicks', (() => { + it('should close when the outside clicks', () => { treeSelect.nativeElement.click(); fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(true); @@ -80,7 +80,7 @@ describe('tree-select component', () => { fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(false); fixture.detectChanges(); - })); + }); it('should disabled work', fakeAsync(() => { expect(treeSelect.nativeElement.classList).toContain('ant-select-enabled'); testComponent.disabled = true; @@ -97,7 +97,7 @@ describe('tree-select component', () => { fixture.detectChanges(); tick(); })); - it('should dropdownMatchSelectWidth work', (() => { + it('should dropdownMatchSelectWidth work', () => { testComponent.dropdownMatchSelectWidth = true; fixture.detectChanges(); treeSelect.nativeElement.click(); @@ -113,7 +113,7 @@ describe('tree-select component', () => { fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(true); expect(overlayPane.style.minWidth).toBe('250px'); - })); + }); it('should clear value work', fakeAsync(() => { testComponent.allowClear = true; fixture.detectChanges(); @@ -154,7 +154,7 @@ describe('tree-select component', () => { fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(true); fixture.detectChanges(); - const targetNode = overlayContainerElement.querySelectorAll('nz-tree-node')[ 2 ]; + const targetNode = overlayContainerElement.querySelectorAll('nz-tree-node')[2]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); flush(); @@ -217,7 +217,7 @@ describe('tree-select component', () => { fixture.detectChanges(); testComponent.multiple = true; fixture.detectChanges(); - testComponent.value = [ '1001', '10001', '100011', '100012' ]; + testComponent.value = ['1001', '10001', '100011', '100012']; fixture.detectChanges(); tick(200); fixture.detectChanges(); @@ -227,10 +227,13 @@ describe('tree-select component', () => { tick(200); fixture.detectChanges(); expect(treeSelect.nativeElement.querySelectorAll('.ant-select-selection__choice').length).toBe(3); - const maxTagPlaceholderElement = treeSelect.nativeElement.querySelectorAll('.ant-select-selection__choice')[ 2 ] + const maxTagPlaceholderElement = treeSelect.nativeElement + .querySelectorAll('.ant-select-selection__choice')[2] .querySelector('.ant-select-selection__choice__content'); expect(maxTagPlaceholderElement).toBeTruthy(); - expect(maxTagPlaceholderElement.innerText.trim()).toBe(`+ ${testComponent.value.length - testComponent.maxTagCount} ...`); + expect(maxTagPlaceholderElement.innerText.trim()).toBe( + `+ ${testComponent.value.length - testComponent.maxTagCount} ...` + ); })); }); @@ -287,7 +290,7 @@ describe('tree-select component', () => { it('should set null value work', fakeAsync(() => { fixture.detectChanges(); - expect(testComponent.value![ 0 ]).toBe('1000122'); + expect(testComponent.value![0]).toBe('1000122'); testComponent.setNull(); fixture.detectChanges(); tick(); @@ -325,7 +328,7 @@ describe('tree-select component', () => { fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(true); fixture.detectChanges(); - const targetNode = overlayContainerElement.querySelectorAll('nz-tree-node')[ 2 ]; + const targetNode = overlayContainerElement.querySelectorAll('nz-tree-node')[2]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); flush(); @@ -333,7 +336,7 @@ describe('tree-select component', () => { })); it('should prevent open the dropdown when click remove', fakeAsync(() => { - testComponent.value = [ '1000122' ]; + testComponent.value = ['1000122']; fixture.detectChanges(); tick(200); fixture.detectChanges(); @@ -363,7 +366,6 @@ describe('tree-select component', () => { expect(overlayContainerElement.querySelector('nz-tree')!.getAttribute('hidden')).toBe(''); expect(overlayContainerElement.querySelector('.ant-select-not-found')).toBeTruthy(); })); - }); describe('form', () => { @@ -425,7 +427,7 @@ describe('tree-select component', () => { fixture.detectChanges(); })); - it('should keep expand state', (() => { + it('should keep expand state', () => { testComponent.expandKeys = []; treeSelect.nativeElement.click(); fixture.detectChanges(); @@ -437,7 +439,7 @@ describe('tree-select component', () => { dispatchMouseEvent(targetSwitcher, 'click'); fixture.detectChanges(); expect(targetSwitcher.classList.contains('ant-select-tree-switcher_open')).toBe(true); - expect(treeSelectComponent.nzDefaultExpandedKeys[ 0 ] === '1001').toBe(true); + expect(treeSelectComponent.nzDefaultExpandedKeys[0] === '1001').toBe(true); treeSelect.nativeElement.click(); fixture.detectChanges(); expect(treeSelectComponent.nzOpen).toBe(false); @@ -446,10 +448,9 @@ describe('tree-select component', () => { targetSwitcher = overlayContainerElement.querySelector('.ant-select-tree-switcher')!; expect(treeSelectComponent.nzOpen).toBe(true); expect(targetSwitcher.classList.contains('ant-select-tree-switcher_open')).toBe(true); - expect(treeSelectComponent.nzDefaultExpandedKeys[ 0 ] === '1001').toBe(true); - })); + expect(treeSelectComponent.nzDefaultExpandedKeys[0] === '1001').toBe(true); + }); }); - }); @Component({ @@ -468,13 +469,14 @@ describe('tree-select component', () => { [nzShowSearch]="showSearch" [nzMultiple]="multiple" [nzMaxTagCount]="maxTagCount" - [nzDropdownStyle]="{ 'height': '120px' }"> + [nzDropdownStyle]="{ height: '120px' }" + > ` }) export class NzTestTreeSelectBasicComponent { @ViewChild(NzTreeSelectComponent) nzSelectTreeComponent: NzTreeSelectComponent; - expandKeys = [ '1001', '10001' ]; + expandKeys = ['1001', '10001']; value: string | string[] | null = '10001'; size = 'default'; allowClear = false; @@ -485,31 +487,31 @@ export class NzTestTreeSelectBasicComponent { maxTagCount = Infinity; nodes = [ { - title : 'root1', - key : '1001', + title: 'root1', + key: '1001', children: [ { - title : 'child1', - key : '10001', + title: 'child1', + key: '10001', children: [ { - title : 'child1.1', - key : '100011', + title: 'child1.1', + key: '100011', children: [] }, { - title : 'child1.2', - key : '100012', + title: 'child1.2', + key: '100012', children: [ { - title : 'grandchild1.2.1', - key : '1000121', - isLeaf : true, + title: 'grandchild1.2.1', + key: '1000121', + isLeaf: true, disabled: true }, { - title : 'grandchild1.2.2', - key : '1000122', + title: 'grandchild1.2.2', + key: '1000122', isLeaf: true } ] @@ -519,22 +521,22 @@ export class NzTestTreeSelectBasicComponent { ] }, { - title : 'root2', - key : '1002', + title: 'root2', + key: '1002', children: [ { - title : 'child2.1', - key : '10021', - children : [], + title: 'child2.1', + key: '10021', + children: [], disableCheckbox: true }, { - title : 'child2.2', - key : '10022', + title: 'child2.2', + key: '10022', children: [ { - title : 'grandchild2.2.1', - key : '100221', + title: 'grandchild2.2.1', + key: '100221', isLeaf: true } ] @@ -558,42 +560,43 @@ export class NzTestTreeSelectBasicComponent { [nzNodes]="nodes" [nzShowSearch]="showSearch" [nzCheckable]="true" - [(ngModel)]="value"> + [(ngModel)]="value" + > ` }) export class NzTestTreeSelectCheckableComponent { @ViewChild(NzTreeSelectComponent) nzSelectTreeComponent: NzTreeSelectComponent; - expandKeys = [ '1001', '10001' ]; - value: string[] | null = [ '1000122' ]; + expandKeys = ['1001', '10001']; + value: string[] | null = ['1000122']; showSearch = false; nodes = [ { - title : 'root1', - key : '1001', + title: 'root1', + key: '1001', children: [ { - title : 'child1', - key : '10001', + title: 'child1', + key: '10001', children: [ { - title : 'child1.1', - key : '100011', + title: 'child1.1', + key: '100011', children: [] }, { - title : 'child1.2', - key : '100012', + title: 'child1.2', + key: '100012', children: [ { - title : 'grandchild1.2.1', - key : '1000121', - isLeaf : true, + title: 'grandchild1.2.1', + key: '1000121', + isLeaf: true, disabled: true }, { - title : 'grandchild1.2.2', - key : '1000122', + title: 'grandchild1.2.2', + key: '1000122', isLeaf: true } ] @@ -603,22 +606,22 @@ export class NzTestTreeSelectCheckableComponent { ] }, { - title : 'root2', - key : '1002', + title: 'root2', + key: '1002', children: [ { - title : 'child2.1', - key : '10021', - children : [], + title: 'child2.1', + key: '10021', + children: [], disableCheckbox: true }, { - title : 'child2.2', - key : '10022', + title: 'child2.2', + key: '10022', children: [ { - title : 'grandchild2.2.1', - key : '100221', + title: 'grandchild2.2.1', + key: '100221', isLeaf: true } ] @@ -636,11 +639,7 @@ export class NzTestTreeSelectCheckableComponent { selector: 'nz-test-tree-select-form', template: `
    - - +
    ` }) @@ -648,16 +647,16 @@ export class NzTestTreeSelectFormComponent { formGroup: FormGroup; nodes = [ { - title : 'root2', - key : '1002', + title: 'root2', + key: '1002', children: [ { title: 'child2.1', - key : '10021' + key: '10021' }, { title: 'child2.2', - key : '10022' + key: '10022' } ] } diff --git a/components/tree/demo/basic-controlled.ts b/components/tree/demo/basic-controlled.ts index 3102235f8f3..6d51c2503e3 100644 --- a/components/tree/demo/basic-controlled.ts +++ b/components/tree/demo/basic-controlled.ts @@ -13,59 +13,66 @@ import { NzFormatEmitEvent } from 'ng-zorro-antd'; [nzSelectedKeys]="defaultSelectedKeys" (nzClick)="nzEvent($event)" (nzExpandChange)="nzEvent($event)" - (nzCheckBoxChange)="nzEvent($event)"> + (nzCheckBoxChange)="nzEvent($event)" + > ` }) - export class NzDemoTreeBasicControlledComponent implements OnInit { - defaultCheckedKeys = [ '0-0-0' ]; - defaultSelectedKeys = [ '0-0-0' ]; - defaultExpandedKeys = [ '0-0', '0-0-0', '0-0-1' ]; + defaultCheckedKeys = ['0-0-0']; + defaultSelectedKeys = ['0-0-0']; + defaultExpandedKeys = ['0-0', '0-0-0', '0-0-1']; - nodes = [ { - title : '0-0', - key : '0-0', - expanded: true, - children: [ { - title : '0-0-0', - key : '0-0-0', + nodes = [ + { + title: '0-0', + key: '0-0', + expanded: true, children: [ - { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, - { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, - { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + { + title: '0-0-0', + key: '0-0-0', + children: [ + { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, + { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, + { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '0-0-1', + children: [ + { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, + { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, + { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '0-0-2', + isLeaf: true + } ] - }, { - title : '0-0-1', - key : '0-0-1', + }, + { + title: '0-1', + key: '0-1', children: [ - { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, - { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, - { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, + { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, + { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } ] - }, { - title : '0-0-2', - key : '0-0-2', + }, + { + title: '0-2', + key: '0-2', isLeaf: true - } ] - }, { - title : '0-1', - key : '0-1', - children: [ - { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, - { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, - { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } - ] - }, { - title : '0-2', - key : '0-2', - isLeaf: true - } ]; + } + ]; nzEvent(event: NzFormatEmitEvent): void { console.log(event); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/basic.ts b/components/tree/demo/basic.ts index aa3d8587b25..4f5028c5820 100644 --- a/components/tree/demo/basic.ts +++ b/components/tree/demo/basic.ts @@ -13,37 +13,42 @@ import { NzFormatEmitEvent, NzTreeNodeOptions, NzTreeComponent } from 'ng-zorro- [nzSelectedKeys]="defaultSelectedKeys" (nzClick)="nzClick($event)" (nzCheckBoxChange)="nzCheck($event)" - (nzExpandChange)="nzCheck($event)"> + (nzExpandChange)="nzCheck($event)" + > ` }) - export class NzDemoTreeBasicComponent implements OnInit { @ViewChild('treeCom') treeCom: NzTreeComponent; - defaultCheckedKeys = [ '10020' ]; - defaultSelectedKeys = [ '10010' ]; - defaultExpandedKeys = [ '100', '1001' ]; + defaultCheckedKeys = ['10020']; + defaultSelectedKeys = ['10010']; + defaultExpandedKeys = ['100', '1001']; - nodes: NzTreeNodeOptions[] = [ { - title : 'parent 1', - key : '100', - children: [ { - title : 'parent 1-0', - key : '1001', - disabled: true, - children: [ - { title: 'leaf 1-0-0', key: '10010', disableCheckbox: true, isLeaf: true }, - { title: 'leaf 1-0-1', key: '10011', isLeaf: true } - ] - }, { - title : 'parent 1-1', - key : '1002', + nodes: NzTreeNodeOptions[] = [ + { + title: 'parent 1', + key: '100', children: [ - { title: 'leaf 1-1-0', key: '10020', isLeaf: true }, - { title: 'leaf 1-1-1', key: '10021', isLeaf: true } + { + title: 'parent 1-0', + key: '1001', + disabled: true, + children: [ + { title: 'leaf 1-0-0', key: '10010', disableCheckbox: true, isLeaf: true }, + { title: 'leaf 1-0-1', key: '10011', isLeaf: true } + ] + }, + { + title: 'parent 1-1', + key: '1002', + children: [ + { title: 'leaf 1-1-0', key: '10020', isLeaf: true }, + { title: 'leaf 1-1-1', key: '10021', isLeaf: true } + ] + } ] - } ] - } ]; + } + ]; nzClick(event: NzFormatEmitEvent): void { console.log(event); @@ -61,7 +66,12 @@ export class NzDemoTreeBasicComponent implements OnInit { ngOnInit(): void { setTimeout(() => { console.log(this.treeCom.getTreeNodeByKey('10011'), 'get nzTreeNode with key'); - console.log(this.treeCom.getTreeNodes(), this.treeCom.getCheckedNodeList(), this.treeCom.getSelectedNodeList(), this.treeCom.getExpandedNodeList()); + console.log( + this.treeCom.getTreeNodes(), + this.treeCom.getCheckedNodeList(), + this.treeCom.getSelectedNodeList(), + this.treeCom.getExpandedNodeList() + ); }, 1500); } } diff --git a/components/tree/demo/customized-icon.ts b/components/tree/demo/customized-icon.ts index 12d4d9a185c..d0fbdb014ef 100644 --- a/components/tree/demo/customized-icon.ts +++ b/components/tree/demo/customized-icon.ts @@ -3,20 +3,16 @@ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nz-demo-tree-customized-icon', template: ` - - + ` }) - export class NzDemoTreeCustomizedIconComponent implements OnInit { nodes = [ { - title : 'parent 1', - key : '100', + title: 'parent 1', + key: '100', expanded: true, - icon : 'anticon anticon-smile-o', + icon: 'anticon anticon-smile-o', children: [ { title: 'leaf', key: '1001', icon: 'anticon anticon-meh-o', isLeaf: true }, { title: 'leaf', key: '1002', icon: 'anticon anticon-frown-o', isLeaf: true } @@ -24,6 +20,5 @@ export class NzDemoTreeCustomizedIconComponent implements OnInit { } ]; - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/directory.ts b/components/tree/demo/directory.ts index 16214d20436..69d5bbc7f07 100644 --- a/components/tree/demo/directory.ts +++ b/components/tree/demo/directory.ts @@ -10,11 +10,7 @@ import { @Component({ selector: 'nz-demo-tree-directory', template: ` - +
    • Action 1
    • @@ -22,83 +18,90 @@ import {
    - - + + - {{node.title}} - created by {{node?.origin?.author | lowercase}} + {{ node.title }} + created by {{ node?.origin?.author | lowercase }} - + - {{node.title}} - modified by {{node?.origin?.author | lowercase}} + {{ node.title }} + modified by {{ node?.origin?.author | lowercase }} -
    `, - styles: [` - :host ::ng-deep .ant-tree { - overflow: hidden; - margin: 0 -24px; - padding: 0 24px; - } +
    + `, + styles: [ + ` + :host ::ng-deep .ant-tree { + overflow: hidden; + margin: 0 -24px; + padding: 0 24px; + } - :host ::ng-deep .ant-tree li { - padding: 4px 0 0 0; - } + :host ::ng-deep .ant-tree li { + padding: 4px 0 0 0; + } - .custom-node { - cursor: pointer; - line-height: 24px; - margin-left: 4px; - display: inline-block; - margin: 0 -1000px; - padding: 0 1000px; - } + .custom-node { + cursor: pointer; + line-height: 24px; + margin-left: 4px; + display: inline-block; + margin: 0 -1000px; + padding: 0 1000px; + } - .active { - background: #1890FF; - color: #fff; - } + .active { + background: #1890ff; + color: #fff; + } - .file-name, .folder-name { - margin-left: 4px; - } + .file-name, + .folder-name { + margin-left: 4px; + } - .file-desc, .folder-desc { - padding: 0 8px; - display: inline-block; - background: #87CEFF; - color: #FFFFFF; - position: relative; - left: 12px; - } - `] + .file-desc, + .folder-desc { + padding: 0 8px; + display: inline-block; + background: #87ceff; + color: #ffffff; + position: relative; + left: 12px; + } + ` + ] }) - export class NzDemoTreeDirectoryComponent { @ViewChild('treeCom') treeCom: NzTreeComponent; dropdown: NzDropdownContextComponent; // actived node activedNode: NzTreeNode; - nodes = [{ - title: 'parent 0', - key: '100', - author: 'NG ZORRO', - expanded: true, - children: [ - {title: 'leaf 0-0', key: '1000', author: 'NG ZORRO', isLeaf: true}, - {title: 'leaf 0-1', key: '1001', author: 'NG ZORRO', isLeaf: true} - ] - }, { - title: 'parent 1', - key: '101', - author: 'NG ZORRO', - children: [ - {title: 'leaf 1-0', key: '1010', author: 'NG ZORRO', isLeaf: true}, - {title: 'leaf 1-1', key: '1011', author: 'NG ZORRO', isLeaf: true} - ] - }]; + nodes = [ + { + title: 'parent 0', + key: '100', + author: 'NG ZORRO', + expanded: true, + children: [ + { title: 'leaf 0-0', key: '1000', author: 'NG ZORRO', isLeaf: true }, + { title: 'leaf 0-1', key: '1001', author: 'NG ZORRO', isLeaf: true } + ] + }, + { + title: 'parent 1', + key: '101', + author: 'NG ZORRO', + children: [ + { title: 'leaf 1-0', key: '1010', author: 'NG ZORRO', isLeaf: true }, + { title: 'leaf 1-1', key: '1011', author: 'NG ZORRO', isLeaf: true } + ] + } + ]; openFolder(data: NzTreeNode | Required): void { // do something if u want @@ -122,6 +125,5 @@ export class NzDemoTreeDirectoryComponent { // do something } - constructor(private nzDropdownService: NzDropdownService) { - } + constructor(private nzDropdownService: NzDropdownService) {} } diff --git a/components/tree/demo/draggable-confirm.ts b/components/tree/demo/draggable-confirm.ts index bad30684024..6db476001f9 100644 --- a/components/tree/demo/draggable-confirm.ts +++ b/components/tree/demo/draggable-confirm.ts @@ -6,34 +6,29 @@ import { delay } from 'rxjs/operators'; @Component({ selector: 'nz-demo-tree-draggable-confirm', template: ` - - + ` }) - export class NzDemoTreeDraggableConfirmComponent implements OnInit { - nodes = [ { - title : '0-0', - key : '100', - expanded: true, - children: [ { - title : '0-0-0', - key : '1001', - children: [ - { title: '0-0-0-0', key: '10010', isLeaf: true }, - { title: '0-0-0-1', key: '10011', isLeaf: true } - ] - }, { - title : '0-0-1', - key : '1002', + nodes = [ + { + title: '0-0', + key: '100', + expanded: true, children: [ - { title: '0-0-1-0', key: '10020', isLeaf: true } + { + title: '0-0-0', + key: '1001', + children: [{ title: '0-0-0-0', key: '10010', isLeaf: true }, { title: '0-0-0-1', key: '10011', isLeaf: true }] + }, + { + title: '0-0-1', + key: '1002', + children: [{ title: '0-0-1-0', key: '10020', isLeaf: true }] + } ] - } ] - } ]; + } + ]; beforeDrop(arg: NzFormatBeforeDropEvent): Observable { // if insert node into another node, wait 1s @@ -44,6 +39,5 @@ export class NzDemoTreeDraggableConfirmComponent implements OnInit { } } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/draggable.ts b/components/tree/demo/draggable.ts index 4a324ff0634..2ddf80817af 100644 --- a/components/tree/demo/draggable.ts +++ b/components/tree/demo/draggable.ts @@ -4,77 +4,83 @@ import { NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-tree-draggable', template: ` - - + `, - styles : [ ` - :host ::ng-deep .draggable-tree .ant-tree-node-content-wrapper { - width: calc(100% - 42px); - } - ` ] + styles: [ + ` + :host ::ng-deep .draggable-tree .ant-tree-node-content-wrapper { + width: calc(100% - 42px); + } + ` + ] }) - export class NzDemoTreeDraggableComponent implements OnInit { @ViewChild('treeCom') treeCom: NzTreeComponent; - nodes = [ { - title : '0-0', - key : '00', - expanded: true, - children: [ { - title : '0-0-0', - key : '000', + nodes = [ + { + title: '0-0', + key: '00', expanded: true, children: [ - { title: '0-0-0-0', key: '0000', isLeaf: true }, - { title: '0-0-0-1', key: '0001', isLeaf: true }, - { title: '0-0-0-2', key: '0002', isLeaf: true } - ] - }, { - title : '0-0-1', - key : '001', - children: [ - { title: '0-0-1-0', key: '0010', isLeaf: true }, - { title: '0-0-1-1', key: '0011', isLeaf: true }, - { title: '0-0-1-2', key: '0012', isLeaf: true } + { + title: '0-0-0', + key: '000', + expanded: true, + children: [ + { title: '0-0-0-0', key: '0000', isLeaf: true }, + { title: '0-0-0-1', key: '0001', isLeaf: true }, + { title: '0-0-0-2', key: '0002', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '001', + children: [ + { title: '0-0-1-0', key: '0010', isLeaf: true }, + { title: '0-0-1-1', key: '0011', isLeaf: true }, + { title: '0-0-1-2', key: '0012', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '002' + } ] - }, { - title: '0-0-2', - key : '002' - } ] - }, { - title : '0-1', - key : '01', - children: [ { - title : '0-1-0', - key : '010', + }, + { + title: '0-1', + key: '01', children: [ - { title: '0-1-0-0', key: '0100', isLeaf: true }, - { title: '0-1-0-1', key: '0101', isLeaf: true }, - { title: '0-1-0-2', key: '0102', isLeaf: true } + { + title: '0-1-0', + key: '010', + children: [ + { title: '0-1-0-0', key: '0100', isLeaf: true }, + { title: '0-1-0-1', key: '0101', isLeaf: true }, + { title: '0-1-0-2', key: '0102', isLeaf: true } + ] + }, + { + title: '0-1-1', + key: '011', + children: [ + { title: '0-1-1-0', key: '0110', isLeaf: true }, + { title: '0-1-1-1', key: '0111', isLeaf: true }, + { title: '0-1-1-2', key: '0112', isLeaf: true } + ] + } ] - }, { - title : '0-1-1', - key : '011', - children: [ - { title: '0-1-1-0', key: '0110', isLeaf: true }, - { title: '0-1-1-1', key: '0111', isLeaf: true }, - { title: '0-1-1-2', key: '0112', isLeaf: true } - ] - } ] - }, { - title : '0-2', - key : '02', - isLeaf: true - } ]; + }, + { + title: '0-2', + key: '02', + isLeaf: true + } + ]; nzEvent(event: NzFormatEmitEvent): void { console.log(event); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/dynamic.ts b/components/tree/demo/dynamic.ts index e7e88eb9c00..9b43f49412e 100644 --- a/components/tree/demo/dynamic.ts +++ b/components/tree/demo/dynamic.ts @@ -4,15 +4,9 @@ import { NzFormatEmitEvent } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-tree-dynamic', template: ` - - + ` }) - export class NzDemoTreeDynamicComponent implements OnInit { nodes = [ { title: 'Expand to load', key: '0' }, @@ -28,12 +22,12 @@ export class NzDemoTreeDynamicComponent implements OnInit { if (event.node.getChildren().length === 0 && event.node.isExpanded) { event.node.addChildren([ { title: 'Child Node', key: `${event.node.key}-0` }, - { title: 'Child Node', key: `${event.node.key}-1` } ]); + { title: 'Child Node', key: `${event.node.key}-1` } + ]); } }, 1000); } } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/line.ts b/components/tree/demo/line.ts index 40c74ca8e76..2459dfeeafb 100644 --- a/components/tree/demo/line.ts +++ b/components/tree/demo/line.ts @@ -4,48 +4,43 @@ import { NzFormatEmitEvent } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-tree-line', template: ` - - + ` }) - export class NzDemoTreeLineComponent implements OnInit { - nodes = [ { - title : 'parent 1', - key : '100', - expanded: true, - children: [ { - title : 'parent 1-0', - key : '1001', + nodes = [ + { + title: 'parent 1', + key: '100', expanded: true, children: [ - { title: 'leaf', key: '10010', isLeaf: true }, - { title: 'leaf', key: '10011', isLeaf: true }, - { title: 'leaf', key: '10012', isLeaf: true } - ] - }, { - title : 'parent 1-1', - key : '1002', - children: [ - { title: 'leaf', key: '10020', isLeaf: true } + { + title: 'parent 1-0', + key: '1001', + expanded: true, + children: [ + { title: 'leaf', key: '10010', isLeaf: true }, + { title: 'leaf', key: '10011', isLeaf: true }, + { title: 'leaf', key: '10012', isLeaf: true } + ] + }, + { + title: 'parent 1-1', + key: '1002', + children: [{ title: 'leaf', key: '10020', isLeaf: true }] + }, + { + title: 'parent 1-2', + key: '1003', + children: [{ title: 'leaf', key: '10030', isLeaf: true }, { title: 'leaf', key: '10031', isLeaf: true }] + } ] - }, { - title : 'parent 1-2', - key : '1003', - children: [ - { title: 'leaf', key: '10030', isLeaf: true }, - { title: 'leaf', key: '10031', isLeaf: true } - ] - } ] - } ]; + } + ]; nzEvent(event: NzFormatEmitEvent): void { console.log(event); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/demo/search.ts b/components/tree/demo/search.ts index 11d902649d4..7100d78ecfe 100644 --- a/components/tree/demo/search.ts +++ b/components/tree/demo/search.ts @@ -5,7 +5,7 @@ import { NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd'; selector: 'nz-demo-tree-search', template: ` - + @@ -16,66 +16,76 @@ import { NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd'; [nzSearchValue]="searchValue" (nzClick)="nzEvent($event)" (nzExpandChange)="nzEvent($event)" - (nzSearchValueChange)="nzEvent($event)"> + (nzSearchValueChange)="nzEvent($event)" + > `, - styles : [ ` - nz-input-group { - padding: 10px 0; - } - ` ] + styles: [ + ` + nz-input-group { + padding: 10px 0; + } + ` + ] }) - export class NzDemoTreeSearchComponent implements OnInit { @ViewChild('treeCom') treeCom: NzTreeComponent; searchValue = ''; - nodes = [ { - title : '0-0', - key : '0-0', - children: [ { - title : '0-0-0', - key : '0-0-0', + nodes = [ + { + title: '0-0', + key: '0-0', children: [ - { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, - { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, - { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + { + title: '0-0-0', + key: '0-0-0', + children: [ + { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, + { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, + { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '0-0-1', + children: [ + { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, + { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, + { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '0-0-2', + isLeaf: true + } ] - }, { - title : '0-0-1', - key : '0-0-1', + }, + { + title: '0-1', + key: '0-1', children: [ - { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, - { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, - { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, + { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, + { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } ] - }, { - title : '0-0-2', - key : '0-0-2', + }, + { + title: '0-2', + key: '0-2', isLeaf: true - } ] - }, { - title : '0-1', - key : '0-1', - children: [ - { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, - { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, - { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } - ] - }, { - title : '0-2', - key : '0-2', - isLeaf: true - } ]; + } + ]; nzEvent(event: NzFormatEmitEvent): void { - console.log(event, + console.log( + event, // tslint:disable-next-line:no-any this.treeCom.getMatchedNodeList().map((v: any) => v.title), this.treeCom.getExpandedNodeList() ); } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/components/tree/nz-tree-base.service.ts b/components/tree/nz-tree-base.service.ts index 0872fdfef33..4312778222b 100644 --- a/components/tree/nz-tree-base.service.ts +++ b/components/tree/nz-tree-base.service.ts @@ -193,7 +193,7 @@ export class NzTreeBaseService implements OnDestroy { } } else { if (node.isSelected && index === -1) { - this.selectedNodeList = [ node ]; + this.selectedNodeList = [node]; } } index = this.selectedNodeList.findIndex(n => node.key === n.key); @@ -427,7 +427,7 @@ export class NzTreeBaseService implements OnDestroy { // until root this.conductUp(node); } else { - node.children.forEach((child) => { + node.children.forEach(child => { this.refreshDragNode(child); }); } @@ -482,14 +482,14 @@ export class NzTreeBaseService implements OnDestroy { } switch (dragPos) { case 0: - targetNode.addChildren([ this.selectedNode ]); + targetNode.addChildren([this.selectedNode]); this.resetNodeLevel(targetNode); break; case -1: case 1: const tIndex = dragPos === 1 ? 1 : 0; if (targetParent) { - targetParent.addChildren([ this.selectedNode ], targetParent.children.indexOf(targetNode) + tIndex); + targetParent.addChildren([this.selectedNode], targetParent.children.indexOf(targetNode) + tIndex); const parent = this.selectedNode.getParentNode(); if (parent) { this.resetNodeLevel(parent); @@ -498,13 +498,13 @@ export class NzTreeBaseService implements OnDestroy { const targetIndex = this.rootNodes.indexOf(targetNode) + tIndex; // 根节点插入 this.rootNodes.splice(targetIndex, 0, this.selectedNode!); - this.rootNodes[ targetIndex ].parentNode = undefined; - this.rootNodes[ targetIndex ].level = 0; + this.rootNodes[targetIndex].parentNode = undefined; + this.rootNodes[targetIndex].level = 0; } break; } // flush all nodes - this.rootNodes.forEach((child) => { + this.rootNodes.forEach(child => { if (!child.treeService) { child.service = treeService || undefined; } @@ -521,9 +521,9 @@ export class NzTreeBaseService implements OnDestroy { */ formatEvent(eventName: string, node?: NzTreeNode, event?: MouseEvent | DragEvent): NzFormatEmitEvent { const emitStructure = { - 'eventName': eventName, - 'node' : node || undefined, - 'event' : event || undefined + eventName, + node: node || undefined, + event: event || undefined }; switch (eventName) { case 'dragstart': @@ -532,29 +532,29 @@ export class NzTreeBaseService implements OnDestroy { case 'dragleave': case 'drop': case 'dragend': - Object.assign(emitStructure, { 'dragNode': this.getSelectedNode() }); + Object.assign(emitStructure, { dragNode: this.getSelectedNode() }); break; case 'click': case 'dblclick': - Object.assign(emitStructure, { 'selectedKeys': this.selectedNodeList }); - Object.assign(emitStructure, { 'nodes': this.selectedNodeList }); - Object.assign(emitStructure, { 'keys': this.selectedNodeList.map(n => n.key) }); + Object.assign(emitStructure, { selectedKeys: this.selectedNodeList }); + Object.assign(emitStructure, { nodes: this.selectedNodeList }); + Object.assign(emitStructure, { keys: this.selectedNodeList.map(n => n.key) }); break; case 'check': const checkedNodeList = this.getCheckedNodeList(); - Object.assign(emitStructure, { 'checkedKeys': checkedNodeList }); - Object.assign(emitStructure, { 'nodes': checkedNodeList }); - Object.assign(emitStructure, { 'keys': checkedNodeList.map(n => n.key) }); + Object.assign(emitStructure, { checkedKeys: checkedNodeList }); + Object.assign(emitStructure, { nodes: checkedNodeList }); + Object.assign(emitStructure, { keys: checkedNodeList.map(n => n.key) }); break; case 'search': - Object.assign(emitStructure, { 'matchedKeys': this.getMatchedNodeList() }); - Object.assign(emitStructure, { 'nodes': this.getMatchedNodeList() }); - Object.assign(emitStructure, { 'keys': this.getMatchedNodeList().map(n => n.key) }); + Object.assign(emitStructure, { matchedKeys: this.getMatchedNodeList() }); + Object.assign(emitStructure, { nodes: this.getMatchedNodeList() }); + Object.assign(emitStructure, { keys: this.getMatchedNodeList().map(n => n.key) }); break; case 'expand': - Object.assign(emitStructure, { 'nodes': this.expandedNodeList }); - Object.assign(emitStructure, { 'keys': this.expandedNodeList.map(n => n.key) }); + Object.assign(emitStructure, { nodes: this.expandedNodeList }); + Object.assign(emitStructure, { keys: this.expandedNodeList.map(n => n.key) }); break; } return emitStructure; @@ -564,5 +564,4 @@ export class NzTreeBaseService implements OnDestroy { this.triggerEventChange$!.complete(); this.triggerEventChange$ = null; } - } diff --git a/components/tree/nz-tree-node.component.ts b/components/tree/nz-tree-node.component.ts index fbab78b46ee..b04cf14a09e 100644 --- a/components/tree/nz-tree-node.component.ts +++ b/components/tree/nz-tree-node.component.ts @@ -25,13 +25,12 @@ import { NzTreeBaseService } from './nz-tree-base.service'; import { NzTreeNode } from './nz-tree-node'; @Component({ - selector : 'nz-tree-node', - templateUrl : './nz-tree-node.component.html', - changeDetection : ChangeDetectionStrategy.OnPush, + selector: 'nz-tree-node', + templateUrl: './nz-tree-node.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, - animations : [ collapseMotion ] + animations: [collapseMotion] }) - export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { @ViewChild('dragElement') dragElement: ElementRef; @@ -96,7 +95,10 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { if (value && this.nzTreeNode.title!.includes(value)) { // match the search value const index = this.nzTreeNode.title.indexOf(value); - this.highlightKeys = [ this.nzTreeNode.title.slice(0, index), this.nzTreeNode.title.slice(index + value.length, this.nzTreeNode.title.length) ]; + this.highlightKeys = [ + this.nzTreeNode.title.slice(0, index), + this.nzTreeNode.title.slice(index + value.length, this.nzTreeNode.title.length) + ]; } this._searchValue = value; } @@ -120,9 +122,9 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { */ destroy$ = new Subject(); dragPos = 2; - dragPosClass: { [ key: string ]: string } = { - '0' : 'drag-over', - '1' : 'drag-over-gap-bottom', + dragPosClass: { [key: string]: string } = { + '0': 'drag-over', + '1': 'drag-over-gap-bottom', '-1': 'drag-over-gap-top' }; @@ -138,7 +140,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { } get canDraggable(): boolean | null { - return (this.nzDraggable && !this.nzTreeNode.isDisabled) ? true : null; + return this.nzDraggable && !this.nzTreeNode.isDisabled ? true : null; } get isShowLineIcon(): boolean { @@ -150,16 +152,18 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { } get isSwitcherOpen(): boolean { - return (this.nzTreeNode.isExpanded && !this.nzTreeNode.isLeaf); + return this.nzTreeNode.isExpanded && !this.nzTreeNode.isLeaf; } get isSwitcherClose(): boolean { - return (!this.nzTreeNode.isExpanded && !this.nzTreeNode.isLeaf); + return !this.nzTreeNode.isExpanded && !this.nzTreeNode.isLeaf; } get displayStyle(): string { // to hide unmatched nodes - return (this.nzSearchValue && this.nzHideUnMatched && !this.nzTreeNode.isMatched && !this.nzTreeNode.isExpanded) ? 'none' : ''; + return this.nzSearchValue && this.nzHideUnMatched && !this.nzTreeNode.isMatched && !this.nzTreeNode.isExpanded + ? 'none' + : ''; } /** @@ -168,44 +172,44 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { setClassMap(): void { this.prefixCls = this.nzSelectMode ? 'ant-select-tree' : 'ant-tree'; this.nzNodeClass = { - [ `${this.prefixCls}-treenode-disabled` ] : this.nzTreeNode.isDisabled, - [ `${this.prefixCls}-treenode-switcher-open` ] : this.isSwitcherOpen, - [ `${this.prefixCls}-treenode-switcher-close` ] : this.isSwitcherClose, - [ `${this.prefixCls}-treenode-checkbox-checked` ] : this.nzTreeNode.isChecked, - [ `${this.prefixCls}-treenode-checkbox-indeterminate` ]: this.nzTreeNode.isHalfChecked, - [ `${this.prefixCls}-treenode-selected` ] : this.nzTreeNode.isSelected, - [ `${this.prefixCls}-treenode-loading` ] : this.nzTreeNode.isLoading + [`${this.prefixCls}-treenode-disabled`]: this.nzTreeNode.isDisabled, + [`${this.prefixCls}-treenode-switcher-open`]: this.isSwitcherOpen, + [`${this.prefixCls}-treenode-switcher-close`]: this.isSwitcherClose, + [`${this.prefixCls}-treenode-checkbox-checked`]: this.nzTreeNode.isChecked, + [`${this.prefixCls}-treenode-checkbox-indeterminate`]: this.nzTreeNode.isHalfChecked, + [`${this.prefixCls}-treenode-selected`]: this.nzTreeNode.isSelected, + [`${this.prefixCls}-treenode-loading`]: this.nzTreeNode.isLoading }; this.nzNodeSwitcherClass = { - [ `${this.prefixCls}-switcher` ] : true, - [ `${this.prefixCls}-switcher-noop` ] : this.nzTreeNode.isLeaf, - [ `${this.prefixCls}-switcher_open` ] : this.isSwitcherOpen, - [ `${this.prefixCls}-switcher_close` ]: this.isSwitcherClose + [`${this.prefixCls}-switcher`]: true, + [`${this.prefixCls}-switcher-noop`]: this.nzTreeNode.isLeaf, + [`${this.prefixCls}-switcher_open`]: this.isSwitcherOpen, + [`${this.prefixCls}-switcher_close`]: this.isSwitcherClose }; this.nzNodeCheckboxClass = { - [ `${this.prefixCls}-checkbox` ] : true, - [ `${this.prefixCls}-checkbox-checked` ] : this.nzTreeNode.isChecked, - [ `${this.prefixCls}-checkbox-indeterminate` ]: this.nzTreeNode.isHalfChecked, - [ `${this.prefixCls}-checkbox-disabled` ] : this.nzTreeNode.isDisabled || this.nzTreeNode.isDisableCheckbox + [`${this.prefixCls}-checkbox`]: true, + [`${this.prefixCls}-checkbox-checked`]: this.nzTreeNode.isChecked, + [`${this.prefixCls}-checkbox-indeterminate`]: this.nzTreeNode.isHalfChecked, + [`${this.prefixCls}-checkbox-disabled`]: this.nzTreeNode.isDisabled || this.nzTreeNode.isDisableCheckbox }; this.nzNodeContentClass = { - [ `${this.prefixCls}-node-content-wrapper` ] : true, - [ `${this.prefixCls}-node-content-wrapper-open` ] : this.isSwitcherOpen, - [ `${this.prefixCls}-node-content-wrapper-close` ]: this.isSwitcherClose, - [ `${this.prefixCls}-node-selected` ] : this.nzTreeNode.isSelected + [`${this.prefixCls}-node-content-wrapper`]: true, + [`${this.prefixCls}-node-content-wrapper-open`]: this.isSwitcherOpen, + [`${this.prefixCls}-node-content-wrapper-close`]: this.isSwitcherClose, + [`${this.prefixCls}-node-selected`]: this.nzTreeNode.isSelected }; this.nzNodeContentIconClass = { - [ `${this.prefixCls}-iconEle` ] : true, - [ `${this.prefixCls}-icon__customize` ]: true + [`${this.prefixCls}-iconEle`]: true, + [`${this.prefixCls}-icon__customize`]: true }; this.nzNodeContentLoadingClass = { - [ `${this.prefixCls}-iconEle` ]: true + [`${this.prefixCls}-iconEle`]: true }; } - @HostListener('mousedown', [ '$event' ]) + @HostListener('mousedown', ['$event']) onMousedown(event: MouseEvent): void { if (this.nzSelectMode) { event.preventDefault(); @@ -215,7 +219,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { /** * click node to select, 200ms to dbl click */ - @HostListener('click', [ '$event' ]) + @HostListener('click', ['$event']) nzClick(event: MouseEvent): void { event.preventDefault(); event.stopPropagation(); @@ -226,7 +230,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { this.nzTreeService!.triggerEventChange$!.next(eventNext); } - @HostListener('dblclick', [ '$event' ]) + @HostListener('dblclick', ['$event']) nzDblClick(event: MouseEvent): void { event.preventDefault(); event.stopPropagation(); @@ -237,7 +241,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { /** * @param event */ - @HostListener('contextmenu', [ '$event' ]) + @HostListener('contextmenu', ['$event']) nzContextMenu(event: MouseEvent): void { event.preventDefault(); event.stopPropagation(); @@ -288,7 +292,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { * @param e */ clearDragClass(): void { - const dragClass = [ 'drag-over-gap-top', 'drag-over-gap-bottom', 'drag-over' ]; + const dragClass = ['drag-over-gap-top', 'drag-over-gap-bottom', 'drag-over']; dragClass.forEach(e => { this.renderer.removeClass(this.dragElement.nativeElement, e); }); @@ -333,7 +337,7 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { this.dragPos = dropPosition; // leaf node will pass if (!(this.dragPos === 0 && this.nzTreeNode.isLeaf)) { - this.renderer.addClass(this.dragElement.nativeElement, this.dragPosClass[ this.dragPos ]); + this.renderer.addClass(this.dragElement.nativeElement, this.dragPosClass[this.dragPos]); } } const eventNext = this.nzTreeService.formatEvent('dragover', this.nzTreeNode, e); @@ -364,8 +368,8 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { if (this.nzBeforeDrop) { this.nzBeforeDrop({ dragNode: this.nzTreeService.getSelectedNode()!, - node : this.nzTreeNode, - pos : this.dragPos + node: this.nzTreeNode, + pos: this.dragPos }).subscribe((canDrop: boolean) => { if (canDrop) { this.nzTreeService.dropAndApply(this.nzTreeNode, this.dragPos); @@ -399,12 +403,24 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { this.ngZone.runOutsideAngular(() => { if (this.nzDraggable) { this.destroy$ = new Subject(); - fromEvent(this.elRef.nativeElement, 'dragstart').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragStart(e)); - fromEvent(this.elRef.nativeElement, 'dragenter').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragEnter(e)); - fromEvent(this.elRef.nativeElement, 'dragover').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragOver(e)); - fromEvent(this.elRef.nativeElement, 'dragleave').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragLeave(e)); - fromEvent(this.elRef.nativeElement, 'drop').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragDrop(e)); - fromEvent(this.elRef.nativeElement, 'dragend').pipe(takeUntil(this.destroy$)).subscribe((e: DragEvent) => this.handleDragEnd(e)); + fromEvent(this.elRef.nativeElement, 'dragstart') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragStart(e)); + fromEvent(this.elRef.nativeElement, 'dragenter') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragEnter(e)); + fromEvent(this.elRef.nativeElement, 'dragover') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragOver(e)); + fromEvent(this.elRef.nativeElement, 'dragleave') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragLeave(e)); + fromEvent(this.elRef.nativeElement, 'drop') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragDrop(e)); + fromEvent(this.elRef.nativeElement, 'dragend') + .pipe(takeUntil(this.destroy$)) + .subscribe((e: DragEvent) => this.handleDragEnd(e)); } else { this.destroy$.next(); this.destroy$.complete(); @@ -422,8 +438,8 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { private renderer: Renderer2, private elRef: ElementRef, private cdr: ChangeDetectorRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngOnInit(): void { // init expanded / selected / checked list @@ -438,13 +454,16 @@ export class NzTreeNodeComponent implements OnInit, OnChanges, OnDestroy { } // TODO this.nzTreeNode.component = this; - this.nzTreeService.eventTriggerChanged().pipe( - filter(data => data.node!.key === this.nzTreeNode.key), - takeUntil(this.destroy$) - ).subscribe(() => { - this.setClassMap(); - this.markForCheck(); - }); + this.nzTreeService + .eventTriggerChanged() + .pipe( + filter(data => data.node!.key === this.nzTreeNode.key), + takeUntil(this.destroy$) + ) + .subscribe(() => { + this.setClassMap(); + this.markForCheck(); + }); this.setClassMap(); } diff --git a/components/tree/nz-tree-node.ts b/components/tree/nz-tree-node.ts index 954ac388f62..1bd3f8cec9c 100644 --- a/components/tree/nz-tree-node.ts +++ b/components/tree/nz-tree-node.ts @@ -15,7 +15,7 @@ export interface NzTreeNodeOptions { children?: NzTreeNodeOptions[]; // tslint:disable-next-line:no-any - [ key: string ]: any; + [key: string]: any; } export class NzTreeNode { @@ -68,7 +68,7 @@ export class NzTreeNode { this._isSelectable = option.disabled || (option.selectable === false ? false : true); this._isDisabled = option.disabled || false; this._isDisableCheckbox = option.disableCheckbox || false; - this._isExpanded = option.isLeaf ? false : (option.expanded || false); + this._isExpanded = option.isLeaf ? false : option.expanded || false; this._isHalfChecked = false; this._isSelected = (!option.disabled && option.selected) || false; this._isLoading = false; @@ -82,16 +82,21 @@ export class NzTreeNode { } else { this.level = 0; } - if (typeof (option.children) !== 'undefined' && option.children !== null) { - option.children.forEach( - (nodeOptions) => { - const s = this.treeService; - if ((s && !s.isCheckStrictly) && option.checked && !option.disabled && !nodeOptions.disabled && !nodeOptions.disableCheckbox) { - nodeOptions.checked = option.checked; - } - this._children.push(new NzTreeNode(nodeOptions, this)); + if (typeof option.children !== 'undefined' && option.children !== null) { + option.children.forEach(nodeOptions => { + const s = this.treeService; + if ( + s && + !s.isCheckStrictly && + option.checked && + !option.disabled && + !nodeOptions.disabled && + !nodeOptions.disableCheckbox + ) { + nodeOptions.checked = option.checked; } - ); + this._children.push(new NzTreeNode(nodeOptions, this)); + }); } } @@ -243,49 +248,51 @@ export class NzTreeNode { // tslint:disable-next-line:no-any public addChildren(children: any[], childPos: number = -1): void { if (!this.isLeaf) { - children.forEach( - (node) => { - const refreshLevel = (n: NzTreeNode) => { - n.getChildren().forEach(c => { - c.level = c.getParentNode()!.level + 1; - // flush origin - c.origin.level = c.level; - refreshLevel(c); - }); - }; - let child = node; - if (child instanceof NzTreeNode) { - child.parentNode = this; - } else { - child = new NzTreeNode(node, this); - } - child.level = this.level + 1; - child.origin.level = child.level; - refreshLevel(child); - try { - childPos === -1 ? this.children.push(child) : this.children.splice(childPos, 0, child); + children.forEach(node => { + const refreshLevel = (n: NzTreeNode) => { + n.getChildren().forEach(c => { + c.level = c.getParentNode()!.level + 1; // flush origin - } catch (e) { - } - }); + c.origin.level = c.level; + refreshLevel(c); + }); + }; + let child = node; + if (child instanceof NzTreeNode) { + child.parentNode = this; + } else { + child = new NzTreeNode(node, this); + } + child.level = this.level + 1; + child.origin.level = child.level; + refreshLevel(child); + try { + childPos === -1 ? this.children.push(child) : this.children.splice(childPos, 0, child); + // flush origin + } catch (e) {} + }); this.origin.children = this.getChildren().map(v => v.origin); // remove loading state this.isLoading = false; this.treeService!.triggerEventChange$!.next({ - 'eventName': 'addChildren', - 'node' : this + eventName: 'addChildren', + node: this }); } } public clearChildren(): void { - this.getChildren().forEach((n) => { + this.getChildren().forEach(n => { this.treeService!.afterRemove(n, false); }); this.getChildren().splice(0, this.getChildren().length); this.origin.children = []; // refresh checked state - this.treeService!.calcCheckedKeys(this.treeService!.checkedNodeList.map(v => v.key!), this.treeService!.rootNodes, this.treeService!.isCheckStrictly); + this.treeService!.calcCheckedKeys( + this.treeService!.checkedNodeList.map(v => v.key!), + this.treeService!.rootNodes, + this.treeService!.isCheckStrictly + ); this.update(); } diff --git a/components/tree/nz-tree-util.ts b/components/tree/nz-tree-util.ts index 07215940f6f..b24c978027b 100644 --- a/components/tree/nz-tree-util.ts +++ b/components/tree/nz-tree-util.ts @@ -7,5 +7,5 @@ export function isCheckDisabled(node: NzTreeNode): boolean { // tslint:disable-next-line:no-any export function isInArray(needle: any, haystack: any[]): boolean { - return (haystack.length > 0 && haystack.indexOf(needle) > -1); + return haystack.length > 0 && haystack.indexOf(needle) > -1; } diff --git a/components/tree/nz-tree.component.ts b/components/tree/nz-tree.component.ts index bfcdedd2fae..5b66b33fac8 100644 --- a/components/tree/nz-tree.component.ts +++ b/components/tree/nz-tree.component.ts @@ -28,36 +28,31 @@ import { NzTreeBaseService } from './nz-tree-base.service'; import { NzTreeNode } from './nz-tree-node'; import { NzTreeService } from './nz-tree.service'; -export function NzTreeServiceFactory(treeSelectService: NzTreeSelectService, treeService: NzTreeService): NzTreeBaseService { +export function NzTreeServiceFactory( + treeSelectService: NzTreeSelectService, + treeService: NzTreeService +): NzTreeBaseService { return treeSelectService ? treeSelectService : treeService; } @Component({ - selector : 'nz-tree', - templateUrl : './nz-tree.component.html', + selector: 'nz-tree', + templateUrl: './nz-tree.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - providers : [ + providers: [ NzTreeService, { - provide : NzTreeBaseService, + provide: NzTreeBaseService, useFactory: NzTreeServiceFactory, - deps : [ - [ - new SkipSelf(), - new Optional(), - NzTreeSelectService - ], - NzTreeService - ] + deps: [[new SkipSelf(), new Optional(), NzTreeSelectService], NzTreeService] }, { - provide : NG_VALUE_ACCESSOR, + provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NzTreeComponent), - multi : true + multi: true } ] }) - export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlValueAccessor { @Input() @InputBoolean() nzShowIcon = false; @Input() @InputBoolean() nzShowLine = false; @@ -76,7 +71,8 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal @Input() @InputBoolean() nzDefaultExpandAll = false; @Input() nzBeforeDrop: (confirm: NzFormatBeforeDropEvent) => Observable; - @Input() @InputBoolean() + @Input() + @InputBoolean() set nzMultiple(value: boolean) { this._nzMultiple = value; this.nzTreeService.isMultiple = value; @@ -92,7 +88,7 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal if (Array.isArray(value)) { if (!this.nzTreeService.isArrayOfNzTreeNode(value)) { // has not been new NzTreeNode - this.nzNodes = value.map(item => (new NzTreeNode(item, undefined, this.nzTreeService))); + this.nzNodes = value.map(item => new NzTreeNode(item, undefined, this.nzTreeService)); } else { this.nzNodes = value.map((item: NzTreeNode) => { item.service = this.nzTreeService; @@ -193,7 +189,7 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal @ContentChild('nzTreeTemplate') nzTreeTemplate: TemplateRef; _searchValue = ''; _nzMultiple: boolean = false; - nzDefaultSubject = new ReplaySubject<{ type: string, keys: string[] }>(6); + nzDefaultSubject = new ReplaySubject<{ type: string; keys: string[] }>(6); destroy$: Subject | null = new Subject(); nzDefaultSubscription: Subscription | null; nzNodes: NzTreeNode[] = []; @@ -252,11 +248,11 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal setClassMap(): void { this.classMap = { - [ this.prefixCls ] : true, - [ this.prefixCls + '-show-line' ]: this.nzShowLine, - [ `${this.prefixCls}-icon-hide` ]: !this.nzShowIcon, - [ 'draggable-tree' ] : this.nzDraggable, - [ 'ant-select-tree' ] : this.nzSelectMode + [this.prefixCls]: true, + [this.prefixCls + '-show-line']: this.nzShowLine, + [`${this.prefixCls}-icon-hide`]: !this.nzShowIcon, + ['draggable-tree']: this.nzDraggable, + ['ant-select-tree']: this.nzSelectMode }; } @@ -288,12 +284,12 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal constructor( public nzTreeService: NzTreeBaseService, private cdr: ChangeDetectorRef, - @Host() @Optional() public noAnimation?: NzNoAnimationDirective) { - } + @Host() @Optional() public noAnimation?: NzNoAnimationDirective + ) {} ngOnInit(): void { this.setClassMap(); - this.nzDefaultSubscription = this.nzDefaultSubject.subscribe((data: { type: string, keys: string[] }) => { + this.nzDefaultSubscription = this.nzDefaultSubject.subscribe((data: { type: string; keys: string[] }) => { if (!data || !data.keys) { return; } @@ -313,49 +309,50 @@ export class NzTreeComponent implements OnInit, OnChanges, OnDestroy, ControlVal } this.cdr.markForCheck(); }); - this.nzTreeService.eventTriggerChanged().pipe( - takeUntil(this.destroy$!) - ).subscribe(data => { - switch (data.eventName) { - case 'expand': - this.nzExpandChange.emit(data); - break; - case 'click': - this.nzClick.emit(data); - break; - case 'check': - this.nzCheckBoxChange.emit(data); - break; - case 'dblclick': - this.nzDblClick.emit(data); - break; - case 'contextmenu': - this.nzContextMenu.emit(data); - break; - // drag drop - case 'dragstart': - this.nzOnDragStart.emit(data); - break; - case 'dragenter': - this.nzOnDragEnter.emit(data); - break; - case 'dragover': - this.nzOnDragOver.emit(data); - break; - case 'dragleave': - this.nzOnDragLeave.emit(data); - break; - case 'drop': - this.nzOnDrop.emit(data); - break; - case 'dragend': - this.nzOnDragEnd.emit(data); - break; - } - }); + this.nzTreeService + .eventTriggerChanged() + .pipe(takeUntil(this.destroy$!)) + .subscribe(data => { + switch (data.eventName) { + case 'expand': + this.nzExpandChange.emit(data); + break; + case 'click': + this.nzClick.emit(data); + break; + case 'check': + this.nzCheckBoxChange.emit(data); + break; + case 'dblclick': + this.nzDblClick.emit(data); + break; + case 'contextmenu': + this.nzContextMenu.emit(data); + break; + // drag drop + case 'dragstart': + this.nzOnDragStart.emit(data); + break; + case 'dragenter': + this.nzOnDragEnter.emit(data); + break; + case 'dragover': + this.nzOnDragOver.emit(data); + break; + case 'dragleave': + this.nzOnDragLeave.emit(data); + break; + case 'drop': + this.nzOnDrop.emit(data); + break; + case 'dragend': + this.nzOnDragEnd.emit(data); + break; + } + }); } - ngOnChanges(changes: { [ propertyName: string ]: SimpleChange }): void { + ngOnChanges(changes: { [propertyName: string]: SimpleChange }): void { if (changes.nzCheckStrictly) { this.nzTreeService.isCheckStrictly = changes.nzCheckStrictly.currentValue; } diff --git a/components/tree/nz-tree.module.ts b/components/tree/nz-tree.module.ts index 6f3f10419bd..07427e32c55 100644 --- a/components/tree/nz-tree.module.ts +++ b/components/tree/nz-tree.module.ts @@ -7,22 +7,8 @@ import { NzTreeNodeComponent } from './nz-tree-node.component'; import { NzTreeComponent } from './nz-tree.component'; @NgModule({ - imports: [ - CommonModule, - NzIconModule, - NzNoAnimationModule, - NzAddOnModule - ], - declarations: [ - NzTreeComponent, - NzTreeNodeComponent - ], - exports: [ - NzTreeComponent, - NzTreeNodeComponent - ] + imports: [CommonModule, NzIconModule, NzNoAnimationModule, NzAddOnModule], + declarations: [NzTreeComponent, NzTreeNodeComponent], + exports: [NzTreeComponent, NzTreeNodeComponent] }) - -export class NzTreeModule { - -} +export class NzTreeModule {} diff --git a/components/tree/nz-tree.service.ts b/components/tree/nz-tree.service.ts index b88266432dc..ffd7addf992 100644 --- a/components/tree/nz-tree.service.ts +++ b/components/tree/nz-tree.service.ts @@ -2,6 +2,4 @@ import { Injectable } from '@angular/core'; import { NzTreeBaseService } from './nz-tree-base.service'; @Injectable() -export class NzTreeService extends NzTreeBaseService { - -} +export class NzTreeService extends NzTreeBaseService {} diff --git a/components/tree/nz-tree.spec.ts b/components/tree/nz-tree.spec.ts index 25555d8500e..5abc419f9c0 100644 --- a/components/tree/nz-tree.spec.ts +++ b/components/tree/nz-tree.spec.ts @@ -23,8 +23,8 @@ describe('nz-tree', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule ], - declarations: [ NzTestTreeBasicControlledComponent ] + imports: [NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule], + declarations: [NzTestTreeBasicControlledComponent] }).compileComponents(); fixture = TestBed.createComponent(NzTestTreeBasicControlledComponent); treeService = fixture.componentInstance.treeComponent.nzTreeService; @@ -44,15 +44,15 @@ describe('nz-tree', () => { expect(treeInstance.treeComponent.getTreeNodes().length).toEqual(3); // checked expect(treeInstance.treeComponent.getCheckedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getCheckedNodeList()[ 0 ].title).toEqual('0-0-0'); + expect(treeInstance.treeComponent.getCheckedNodeList()[0].title).toEqual('0-0-0'); // half expanded expect(treeInstance.treeComponent.getHalfCheckedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getHalfCheckedNodeList()[ 0 ].title).toEqual('0-0'); + expect(treeInstance.treeComponent.getHalfCheckedNodeList()[0].title).toEqual('0-0'); // expanded expect(treeInstance.treeComponent.getExpandedNodeList().length).toEqual(2); // selected expect(treeInstance.treeComponent.getSelectedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getSelectedNodeList()[ 0 ].title).toEqual('0-0-0-0'); + expect(treeInstance.treeComponent.getSelectedNodeList()[0].title).toEqual('0-0-0-0'); // won't affect treeInstance.defaultExpandedKeys = []; @@ -60,7 +60,6 @@ describe('nz-tree', () => { tick(); fixture.detectChanges(); expect(treeInstance.treeComponent.getExpandedNodeList().length).toEqual(0); - })); it('test unCorrectly ngModel', () => { @@ -72,44 +71,51 @@ describe('nz-tree', () => { }); it('test new NzTreeNode of nzData', fakeAsync(() => { - treeInstance.nodes = [ { - title : '0-0', - key : '0-0', - expanded: true, - children: [ { - title : '0-0-0', - key : '0-0-0', + treeInstance.nodes = [ + { + title: '0-0', + key: '0-0', expanded: true, - checked : true, children: [ - { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, - { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, - { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + { + title: '0-0-0', + key: '0-0-0', + expanded: true, + checked: true, + children: [ + { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, + { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, + { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '0-0-1', + selected: true, + children: [ + { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, + { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, + { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '0-0-2', + isLeaf: true + } ] - }, { - title : '0-0-1', - key : '0-0-1', - selected: true, + }, + { + title: '0-1', + key: '0-1', children: [ - { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, - { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, - { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, + { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, + { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } ] - }, { - title : '0-0-2', - key : '0-0-2', - isLeaf: true - } ] - }, { - title : '0-1', - key : '0-1', - children: [ - { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, - { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, - { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } - ] - } ].map(v => { - return (new NzTreeNode(v, undefined, treeService)); + } + ].map(v => { + return new NzTreeNode(v, undefined, treeService); }); fixture.detectChanges(); tick(100); @@ -120,17 +126,17 @@ describe('nz-tree', () => { expect(treeInstance.treeComponent.getMatchedNodeList().length).toEqual(0); // // checked nodes no effect expect(treeInstance.treeComponent.getCheckedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getCheckedNodeList()[ 0 ].title).toEqual('0-0-0'); + expect(treeInstance.treeComponent.getCheckedNodeList()[0].title).toEqual('0-0-0'); expect(treeInstance.treeComponent.getHalfCheckedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getHalfCheckedNodeList()[ 0 ].title).toEqual('0-0'); + expect(treeInstance.treeComponent.getHalfCheckedNodeList()[0].title).toEqual('0-0'); })); it('test click event', fakeAsync(() => { fixture.detectChanges(); const clickSpy = spyOn(treeInstance, 'nzEvent'); // click 0-0-0 to select - let targetNode = treeElement.querySelectorAll('nz-tree-node')[ 1 ]; + let targetNode = treeElement.querySelectorAll('nz-tree-node')[1]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); // 0-0-0 / 0-0-0-0 are selected @@ -144,7 +150,7 @@ describe('nz-tree', () => { expect(clickSpy).toHaveBeenCalledTimes(2); // double click 0-0-0, only response once - targetNode = treeElement.querySelectorAll('nz-tree-node')[ 1 ]; + targetNode = treeElement.querySelectorAll('nz-tree-node')[1]; dispatchMouseEvent(targetNode, 'dblclick'); fixture.detectChanges(); // 0-0-0-0 are selected @@ -153,7 +159,9 @@ describe('nz-tree', () => { expect(clickSpy).toHaveBeenCalledTimes(3); // will detect dblclick // click disabled node - targetNode = treeElement.querySelectorAll('nz-tree-node')[ treeElement.querySelectorAll('nz-tree-node').length - 1 ]; + targetNode = treeElement.querySelectorAll('nz-tree-node')[ + treeElement.querySelectorAll('nz-tree-node').length - 1 + ]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(treeElement.querySelectorAll('.ant-tree-node-selected').length).toEqual(1); @@ -161,15 +169,15 @@ describe('nz-tree', () => { // set nzMultiple to false, click 0-0-0-0 will just active one node treeInstance.multiple = false; fixture.detectChanges(); - targetNode = treeElement.querySelectorAll('nz-tree-node')[ 0 ]; + targetNode = treeElement.querySelectorAll('nz-tree-node')[0]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(treeElement.querySelectorAll('.ant-tree-node-selected').length).toEqual(1); expect(treeInstance.treeComponent.getSelectedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getSelectedNodeList()[ 0 ].title).toEqual('0-0'); + expect(treeInstance.treeComponent.getSelectedNodeList()[0].title).toEqual('0-0'); // cancel selected - targetNode = treeElement.querySelectorAll('nz-tree-node')[ 0 ]; + targetNode = treeElement.querySelectorAll('nz-tree-node')[0]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(treeElement.querySelectorAll('.ant-tree-node-selected').length).toEqual(0); @@ -179,7 +187,7 @@ describe('nz-tree', () => { it('test expand event', fakeAsync(() => { fixture.detectChanges(); // expand 0-0,now 3 nodes expanded - const targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[ 0 ]; + const targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[0]; expect(fixture.componentInstance.treeComponent.getExpandedNodeList().length).toEqual(2); dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); @@ -190,7 +198,7 @@ describe('nz-tree', () => { it('test check event', fakeAsync(() => { fixture.detectChanges(); // uncheck 0-0-0 - let targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ 1 ]; + let targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[1]; expect(fixture.componentInstance.treeComponent.getCheckedNodeList().length).toEqual(1); dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); @@ -198,7 +206,7 @@ describe('nz-tree', () => { expect(treeElement.querySelectorAll('.ant-tree-checkbox-checked').length).toEqual(0); // check 0-0-0, will make 0-0 indeterminate - targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ 1 ]; + targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[1]; dispatchMouseEvent(targetNode, 'click'); tick(300); fixture.detectChanges(); @@ -211,17 +219,17 @@ describe('nz-tree', () => { treeInstance.checkStrictly = true; treeInstance.nodes = [ { - title : 'parent', - key : '0', + title: 'parent', + key: '0', children: [ { - title : 'child 1', - key : '0-0', + title: 'child 1', + key: '0-0', isLeaf: true }, { - title : 'child 2', - key : '0-1', + title: 'child 2', + key: '0-1', isLeaf: true } ] @@ -231,25 +239,24 @@ describe('nz-tree', () => { tick(); fixture.detectChanges(); // check node will not affect other nodes - let targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ 0 ]; + let targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[0]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(fixture.componentInstance.treeComponent.getCheckedNodeList().length).toEqual(1); expect(treeElement.querySelectorAll('.ant-tree-checkbox-checked').length).toEqual(1); - targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ 1 ]; + targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[1]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(fixture.componentInstance.treeComponent.getCheckedNodeList().length).toEqual(2); expect(treeElement.querySelectorAll('.ant-tree-checkbox-checked').length).toEqual(2); - })); it('test contextmenu event', fakeAsync(() => { fixture.detectChanges(); const clickSpy = spyOn(treeInstance, 'nzEvent'); // contextmenu 0-0-0 - const targetNode = treeElement.querySelectorAll('nz-tree-node')[ 1 ]; + const targetNode = treeElement.querySelectorAll('nz-tree-node')[1]; dispatchMouseEvent(targetNode, 'contextmenu'); fixture.detectChanges(); expect(clickSpy).toHaveBeenCalledTimes(1); @@ -259,7 +266,9 @@ describe('nz-tree', () => { fixture.detectChanges(); const clickSpy = spyOn(treeInstance, 'nzEvent'); // contextmenu 0-0-0 - const targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ treeElement.querySelectorAll('li').length - 1 ]; + const targetNode = treeElement.querySelectorAll('.ant-tree-checkbox')[ + treeElement.querySelectorAll('li').length - 1 + ]; dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(clickSpy).toHaveBeenCalledTimes(0); @@ -294,7 +303,7 @@ describe('nz-tree', () => { fixture.detectChanges(); tick(); fixture.detectChanges(); - let targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[ 0 ]; + let targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[0]; dispatchMouseEvent(targetNode, 'click'); tick(); fixture.detectChanges(); @@ -302,26 +311,30 @@ describe('nz-tree', () => { expect(treeElement.querySelectorAll('.ant-tree-switcher_open').length).toEqual(1); expect(fixture.componentInstance.treeComponent.getExpandedNodeList().length).toEqual(1); // add children to clear loading state - fixture.componentInstance.treeComponent.getExpandedNodeList()[ 0 ].addChildren([ { - title: 'Child Node', - key : `0-0` - } ]); + fixture.componentInstance.treeComponent.getExpandedNodeList()[0].addChildren([ + { + title: 'Child Node', + key: `0-0` + } + ]); fixture.detectChanges(); expect(treeElement.querySelectorAll('.ant-tree-treenode-loading').length).toEqual(0); expect(fixture.componentInstance.treeComponent.getExpandedNodeList().length).toEqual(1); // add nzTreeNode children to clear loading state - targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[ 2 ]; + targetNode = treeElement.querySelectorAll('.ant-tree-switcher')[2]; dispatchMouseEvent(targetNode, 'click'); tick(); fixture.detectChanges(); // getExpandedNodeList return ['0', '1'] expect(fixture.componentInstance.treeComponent.getExpandedNodeList().length).toEqual(2); expect(treeElement.querySelectorAll('.ant-tree-treenode-loading').length).toEqual(1); - fixture.componentInstance.treeComponent.getExpandedNodeList()[ 1 ].addChildren([ new NzTreeNode({ - title: 'Child Node', - key : `1-0` - }) ]); + fixture.componentInstance.treeComponent.getExpandedNodeList()[1].addChildren([ + new NzTreeNode({ + title: 'Child Node', + key: `1-0` + }) + ]); fixture.detectChanges(); expect(treeElement.querySelectorAll('.ant-tree-treenode-loading').length).toEqual(0); expect(treeElement.querySelectorAll('.ant-tree-switcher_open').length).toEqual(2); @@ -333,10 +346,12 @@ describe('nz-tree', () => { const node = fixture.componentInstance.treeComponent.getTreeNodeByKey('0-0')!; node.title = '0-0-reset'; fixture.detectChanges(); - expect(treeElement.querySelectorAll('[title=\'0-0-reset\']').length).toEqual(1); + expect(treeElement.querySelectorAll("[title='0-0-reset']").length).toEqual(1); node.isDisabled = true; fixture.detectChanges(); - expect(treeElement.querySelector('.ant-tree-treenode-disabled')!.querySelectorAll('[title=\'0-0-reset\']').length).toEqual(1); + expect( + treeElement.querySelector('.ant-tree-treenode-disabled')!.querySelectorAll("[title='0-0-reset']").length + ).toEqual(1); })); }); @@ -346,11 +361,9 @@ describe('nz-tree', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ NzTestTreeDraggableComponent ], - providers : [ - NzTreeBaseService - ] + imports: [NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule, NzIconTestModule], + declarations: [NzTestTreeDraggableComponent], + providers: [NzTreeBaseService] }).compileComponents(); })); @@ -374,17 +387,17 @@ describe('nz-tree', () => { const dragLeaveSpy = spyOn(treeInstance, 'onDragLeave'); const dropSpy = spyOn(treeInstance, 'onDrop'); const dragEndSpy = spyOn(treeInstance, 'onDragEnd'); - let dragNode = treeElement.querySelector('[title=\'0-1\']')!; - let dropNode = treeElement.querySelector('[title=\'0-0\']')!; - let passNode = treeElement.querySelector('[title=\'0-0-0\']')!; + let dragNode = treeElement.querySelector("[title='0-1']")!; + let dropNode = treeElement.querySelector("[title='0-0']")!; + let passNode = treeElement.querySelector("[title='0-0-0']")!; dispatchTouchEvent(dragNode, 'dragstart'); dispatchTouchEvent(dropNode, 'dragenter'); fixture.detectChanges(); // drag - dragenter - dragNode = treeElement.querySelector('[title=\'0-1\']')!; - dropNode = treeElement.querySelector('[title=\'0-0\']')!; + dragNode = treeElement.querySelector("[title='0-1']")!; + dropNode = treeElement.querySelector("[title='0-0']")!; expect(dragNode.previousElementSibling!.classList).toContain('ant-tree-switcher_close'); expect(dropNode.previousElementSibling!.classList).toContain('ant-tree-switcher_open'); expect(dragStartSpy).toHaveBeenCalledTimes(1); @@ -393,23 +406,23 @@ describe('nz-tree', () => { // dragover dispatchTouchEvent(passNode, 'dragover'); fixture.detectChanges(); - passNode = treeElement.querySelector('[title=\'0-0-0\']')!; + passNode = treeElement.querySelector("[title='0-0-0']")!; expect(passNode.parentElement!.classList).toContain('drag-over'); expect(dragOverSpy).toHaveBeenCalledTimes(1); // dragleave dispatchTouchEvent(passNode, 'dragleave'); fixture.detectChanges(); - passNode = treeElement.querySelector('[title=\'0-0-0\']')!; + passNode = treeElement.querySelector("[title='0-0-0']")!; expect(passNode.parentElement!.classList.contains('drag-over')).toEqual(false); expect(dragLeaveSpy).toHaveBeenCalledTimes(1); // drop 0-1 to 0-0 dispatchTouchEvent(dropNode, 'drop'); fixture.detectChanges(); - dropNode = treeElement.querySelector('[title=\'0-0\']')!; + dropNode = treeElement.querySelector("[title='0-0']")!; expect(dropSpy).toHaveBeenCalledTimes(1); - expect(dropNode.parentElement!.querySelector('[title=\'0-1\']')).toBeDefined(); + expect(dropNode.parentElement!.querySelector("[title='0-1']")).toBeDefined(); // dragend dispatchTouchEvent(dropNode, 'dragend'); @@ -417,43 +430,43 @@ describe('nz-tree', () => { expect(dragEndSpy).toHaveBeenCalledTimes(1); // drag 0-0 child node to 0-1 - dragNode = treeElement.querySelector('[title=\'0-0-0\']')!; - dropNode = treeElement.querySelector('[title=\'0-1\']')!; + dragNode = treeElement.querySelector("[title='0-0-0']")!; + dropNode = treeElement.querySelector("[title='0-1']")!; dispatchTouchEvent(dragNode, 'dragstart'); dispatchTouchEvent(dropNode, 'dragover'); dispatchTouchEvent(dropNode, 'drop'); fixture.detectChanges(); - dropNode = treeElement.querySelector('[title=\'0-1\']')!; + dropNode = treeElement.querySelector("[title='0-1']")!; expect(dropSpy).toHaveBeenCalledTimes(2); - expect(dropNode.parentElement!.querySelector('[title=\'0-0-0\']')).toBeDefined(); + expect(dropNode.parentElement!.querySelector("[title='0-0-0']")).toBeDefined(); })); // can not dispatchTouchEvent with pos, test alone it('test drag drop with dragPos', () => { // init selected node const treeNodes = treeInstance.treeComponent.getTreeNodes(); - const dragNode = treeElement.querySelectorAll('li')[ 1 ]; + const dragNode = treeElement.querySelectorAll('li')[1]; dispatchTouchEvent(dragNode, 'dragstart'); fixture.detectChanges(); // drop 0-0-0 to 0-0 pre - let targetNode = treeNodes[ 0 ]; // 0-0 - treeService = treeNodes[ 1 ].treeService!; + let targetNode = treeNodes[0]; // 0-0 + treeService = treeNodes[1].treeService!; treeService.dropAndApply(targetNode, -1); - expect(treeNodes[ 0 ].title).toEqual('0-0-0'); - expect(treeNodes[ 0 ].level).toEqual(0); + expect(treeNodes[0].title).toEqual('0-0-0'); + expect(treeNodes[0].level).toEqual(0); // drop 0-0-0 to 0-0-1 next - treeService.selectedNode = treeNodes[ 0 ]; - targetNode = treeNodes[ 1 ].getChildren()[ 0 ]; // 0-0-1 + treeService.selectedNode = treeNodes[0]; + targetNode = treeNodes[1].getChildren()[0]; // 0-0-1 treeService.dropAndApply(targetNode, 1); - expect(treeNodes[ 0 ].getChildren()[ 1 ].title).toEqual('0-0-0'); - expect(treeNodes[ 0 ].getChildren()[ 1 ].level).toEqual(1); + expect(treeNodes[0].getChildren()[1].title).toEqual('0-0-0'); + expect(treeNodes[0].getChildren()[1].level).toEqual(1); // drop 0-0-1 to 0-0-0 next - treeService.selectedNode = treeNodes[ 0 ].getChildren()[ 0 ]; - targetNode = treeNodes[ 0 ].getChildren()[ 1 ]; // 0-0-1 + treeService.selectedNode = treeNodes[0].getChildren()[0]; + targetNode = treeNodes[0].getChildren()[1]; // 0-0-1 treeService.dropAndApply(targetNode, 1); - expect(treeNodes[ 0 ].getChildren()[ 0 ].title).toEqual('0-0-0'); + expect(treeNodes[0].getChildren()[0].title).toEqual('0-0-0'); }); it('test wrong drag event', fakeAsync(() => { @@ -461,17 +474,17 @@ describe('nz-tree', () => { fixture.detectChanges(); const dropSpy = spyOn(treeInstance, 'onDrop'); const dragEndSpy = spyOn(treeInstance, 'onDragEnd'); - const dragNode = treeElement.querySelector('[title=\'0-1\']')!; - let dropNode = treeElement.querySelector('[title=\'0-2\']')!; + const dragNode = treeElement.querySelector("[title='0-1']")!; + let dropNode = treeElement.querySelector("[title='0-2']")!; // drop 0-1 to 0-2(leaf node) dispatchTouchEvent(dragNode, 'dragstart'); dispatchTouchEvent(dropNode, 'dragover'); dispatchTouchEvent(dropNode, 'drop'); fixture.detectChanges(); - dropNode = treeElement.querySelector('[title=\'0-2\']')!; + dropNode = treeElement.querySelector("[title='0-2']")!; expect(dropSpy).toHaveBeenCalledTimes(0); - expect(dropNode.parentElement!.querySelector('[title=\'0-1\']')).toBeNull(); + expect(dropNode.parentElement!.querySelector("[title='0-1']")).toBeNull(); // dragend dispatchTouchEvent(dropNode, 'dragend'); fixture.detectChanges(); @@ -489,8 +502,8 @@ describe('nz-tree', () => { })); it('test drag event nzBeforeDrop', () => { - const dragNode = treeElement.querySelector('[title=\'0-2\']')!; - let dropNode = treeElement.querySelector('[title=\'0-1\']')!; + const dragNode = treeElement.querySelector("[title='0-2']")!; + let dropNode = treeElement.querySelector("[title='0-1']")!; treeInstance.beforeDrop = (): Observable => { return of(true); }; @@ -501,10 +514,9 @@ describe('nz-tree', () => { // drop 0-2 to 0-1 dispatchTouchEvent(dropNode, 'drop'); fixture.detectChanges(); - dropNode = treeElement.querySelector('[title=\'0-1\']')!; - expect(dropNode.parentElement!.querySelector('[title=\'0-2\']')).toBeDefined(); + dropNode = treeElement.querySelector("[title='0-1']")!; + expect(dropNode.parentElement!.querySelector("[title='0-2']")).toBeDefined(); }); - }); describe('test older node property', () => { @@ -513,11 +525,9 @@ describe('nz-tree', () => { beforeEach(async(() => { TestBed.configureTestingModule({ - imports : [ NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule, NzIconTestModule ], - declarations: [ NzTestTreeOlderComponent ], - providers : [ - NzTreeBaseService - ] + imports: [NzTreeModule, NoopAnimationsModule, FormsModule, ReactiveFormsModule, NzIconTestModule], + declarations: [NzTestTreeOlderComponent], + providers: [NzTreeBaseService] }).compileComponents(); })); @@ -542,15 +552,15 @@ describe('nz-tree', () => { it('should get correctly nodes', () => { fixture.detectChanges(); - fixture.componentInstance.checkedKeys = [ ...fixture.componentInstance.checkedKeys ]; - fixture.componentInstance.expandKeys = [ ...fixture.componentInstance.expandKeys ]; - fixture.componentInstance.selectedKeys = [ ...fixture.componentInstance.selectedKeys ]; + fixture.componentInstance.checkedKeys = [...fixture.componentInstance.checkedKeys]; + fixture.componentInstance.expandKeys = [...fixture.componentInstance.expandKeys]; + fixture.componentInstance.selectedKeys = [...fixture.componentInstance.selectedKeys]; fixture.detectChanges(); setTimeout(() => { expect(fixture.componentInstance.treeComponent.getCheckedNodeList().length).toEqual(1); - expect(fixture.componentInstance.treeComponent.getCheckedNodeList()[ 0 ].key).toEqual('10001'); + expect(fixture.componentInstance.treeComponent.getCheckedNodeList()[0].key).toEqual('10001'); expect(treeInstance.treeComponent.getHalfCheckedNodeList().length).toEqual(1); - expect(treeInstance.treeComponent.getHalfCheckedNodeList()[ 0 ].key).toEqual('1001'); + expect(treeInstance.treeComponent.getHalfCheckedNodeList()[0].key).toEqual('1001'); expect(fixture.componentInstance.treeComponent.getExpandedNodeList().length).toEqual(2); expect(fixture.componentInstance.treeComponent.getSelectedNodeList().length).toEqual(2); }); @@ -558,9 +568,9 @@ describe('nz-tree', () => { it('test node function', fakeAsync(() => { fixture.detectChanges(); - fixture.componentInstance.checkedKeys = [ ...fixture.componentInstance.checkedKeys ]; - fixture.componentInstance.expandKeys = [ ...fixture.componentInstance.expandKeys ]; - fixture.componentInstance.selectedKeys = [ ...fixture.componentInstance.selectedKeys ]; + fixture.componentInstance.checkedKeys = [...fixture.componentInstance.checkedKeys]; + fixture.componentInstance.expandKeys = [...fixture.componentInstance.expandKeys]; + fixture.componentInstance.selectedKeys = [...fixture.componentInstance.selectedKeys]; fixture.detectChanges(); // get node by key let node = fixture.componentInstance.treeComponent.getTreeNodeByKey('10001')!; @@ -570,20 +580,24 @@ describe('nz-tree', () => { expect(node.getChildren().length).toEqual(0); // remove self node.remove(); - expect(node.getParentNode()!.getChildren().findIndex(v => v.key === node.key)).toEqual(-1); + expect( + node + .getParentNode()! + .getChildren() + .findIndex(v => v.key === node.key) + ).toEqual(-1); // test selectable false and click it node = fixture.componentInstance.treeComponent.getTreeNodeByKey('1001')!; node.isSelectable = false; fixture.detectChanges(); // add nzTreeNode children to clear loading state, root click will not change - const targetNode = treeElement.querySelectorAll('li')[ 0 ]; + const targetNode = treeElement.querySelectorAll('li')[0]; expect(targetNode.querySelectorAll('.ant-tree-treenode-selected').length).toEqual(0); dispatchMouseEvent(targetNode, 'click'); fixture.detectChanges(); expect(targetNode.querySelectorAll('.ant-tree-treenode-selected').length).toEqual(0); })); }); - }); @Component({ @@ -606,11 +620,11 @@ describe('nz-tree', () => { (nzDblClick)="nzEvent($event)" (nzContextMenu)="nzEvent($event)" (nzExpandChange)="nzEvent($event)" - (nzCheckBoxChange)="nzEvent($event)"> + (nzCheckBoxChange)="nzEvent($event)" + > ` }) - export class NzTestTreeBasicControlledComponent { @ViewChild('treeComponent') treeComponent: NzTreeComponent; searchValue: null | string; @@ -618,54 +632,60 @@ export class NzTestTreeBasicControlledComponent { expandAll = false; asyncData = false; checkStrictly = false; - defaultCheckedKeys = [ '0-0-0' ]; - defaultSelectedKeys = [ '0-0-0-0' ]; - defaultExpandedKeys = [ '0-0-0', '0-0-1' ]; + defaultCheckedKeys = ['0-0-0']; + defaultSelectedKeys = ['0-0-0-0']; + defaultExpandedKeys = ['0-0-0', '0-0-1']; // tslint:disable-next-line:no-any - nodes: any = [ { - title : '0-0', - key : '0-0', - expanded: true, - children: [ { - title : '0-0-0', - key : '0-0-0', + nodes: any = [ + { + title: '0-0', + key: '0-0', + expanded: true, children: [ - { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, - { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, - { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + { + title: '0-0-0', + key: '0-0-0', + children: [ + { title: '0-0-0-0', key: '0-0-0-0', isLeaf: true }, + { title: '0-0-0-1', key: '0-0-0-1', isLeaf: true }, + { title: '0-0-0-2', key: '0-0-0-2', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '0-0-1', + children: [ + { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, + { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, + { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '0-0-2', + isLeaf: true + } ] - }, { - title : '0-0-1', - key : '0-0-1', + }, + { + title: '0-1', + key: '0-1', children: [ - { title: '0-0-1-0', key: '0-0-1-0', isLeaf: true }, - { title: '0-0-1-1', key: '0-0-1-1', isLeaf: true }, - { title: '0-0-1-2', key: '0-0-1-2', isLeaf: true } + { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, + { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, + { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } ] - }, { - title : '0-0-2', - key : '0-0-2', + }, + { + title: '0-2', + key: '0-2', + disabled: true, isLeaf: true - } ] - }, { - title : '0-1', - key : '0-1', - children: [ - { title: '0-1-0-0', key: '0-1-0-0', isLeaf: true }, - { title: '0-1-0-1', key: '0-1-0-1', isLeaf: true }, - { title: '0-1-0-2', key: '0-1-0-2', isLeaf: true } - ] - }, { - title : '0-2', - key : '0-2', - disabled: true, - isLeaf : true - } ]; - - nzEvent(): void { - } + } + ]; + nzEvent(): void {} } // ------------------------------------------- @@ -684,84 +704,89 @@ export class NzTestTreeBasicControlledComponent { (nzOnDragLeave)="onDragLeave($event)" (nzOnDragOver)="onDragOver($event)" (nzOnDrop)="onDrop($event)" - (nzOnDragEnd)="onDragEnd($event)"> + (nzOnDragEnd)="onDragEnd($event)" + > ` }) - export class NzTestTreeDraggableComponent { @ViewChild(NzTreeComponent) treeComponent: NzTreeComponent; - nodes = [ { - title : '0-0', - key : '00', - icon : 'anticon anticon-smile', - expanded: true, - children: [ { - title : '0-0-0', - key : '000', - icon : 'smile', + nodes = [ + { + title: '0-0', + key: '00', + icon: 'anticon anticon-smile', expanded: true, children: [ - { title: '0-0-0-0', key: '0000', isLeaf: true }, - { title: '0-0-0-1', key: '0001', isLeaf: true }, - { title: '0-0-0-2', key: '0002', isLeaf: true } - ] - }, { - title : '0-0-1', - key : '001', - children: [ - { title: '0-0-1-0', key: '0010', isLeaf: true }, - { title: '0-0-1-1', key: '0011', isLeaf: true }, - { title: '0-0-1-2', key: '0012', isLeaf: true } - ] - }, { - title: '0-0-2', - key : '002' - } ] - }, { - title : '0-1', - key : '01', - children: [ { - title : '0-1-0', - key : '010', - children: [ - { title: '0-1-0-0', key: '0100', isLeaf: true }, - { title: '0-1-0-1', key: '0101', isLeaf: true }, - { title: '0-1-0-2', key: '0102', isLeaf: true } + { + title: '0-0-0', + key: '000', + icon: 'smile', + expanded: true, + children: [ + { title: '0-0-0-0', key: '0000', isLeaf: true }, + { title: '0-0-0-1', key: '0001', isLeaf: true }, + { title: '0-0-0-2', key: '0002', isLeaf: true } + ] + }, + { + title: '0-0-1', + key: '001', + children: [ + { title: '0-0-1-0', key: '0010', isLeaf: true }, + { title: '0-0-1-1', key: '0011', isLeaf: true }, + { title: '0-0-1-2', key: '0012', isLeaf: true } + ] + }, + { + title: '0-0-2', + key: '002' + } ] - }, { - title : '0-1-1', - key : '011', + }, + { + title: '0-1', + key: '01', children: [ - { title: '0-1-1-0', key: '0110', isLeaf: true }, - { title: '0-1-1-1', key: '0111', isLeaf: true }, - { title: '0-1-1-2', key: '0112', isLeaf: true } + { + title: '0-1-0', + key: '010', + children: [ + { title: '0-1-0-0', key: '0100', isLeaf: true }, + { title: '0-1-0-1', key: '0101', isLeaf: true }, + { title: '0-1-0-2', key: '0102', isLeaf: true } + ] + }, + { + title: '0-1-1', + key: '011', + children: [ + { title: '0-1-1-0', key: '0110', isLeaf: true }, + { title: '0-1-1-1', key: '0111', isLeaf: true }, + { title: '0-1-1-2', key: '0112', isLeaf: true } + ] + } ] - } ] - }, { - title : '0-2', - key : '02', - isLeaf: true - } ]; + }, + { + title: '0-2', + key: '02', + isLeaf: true + } + ]; beforeDrop: () => Observable; - onDragStart(): void { - } + onDragStart(): void {} - onDragEnter(): void { - } + onDragEnter(): void {} - onDragOver(): void { - } + onDragOver(): void {} - onDragLeave(): void { - } + onDragLeave(): void {} - onDrop(): void { - } + onDrop(): void {} - onDragEnd(): void { - } + onDragEnd(): void {} } // ------------------------------------------- @@ -776,15 +801,16 @@ export class NzTestTreeDraggableComponent { [nzDefaultExpandedKeys]="expandKeys" [nzDefaultCheckedKeys]="checkedKeys" [nzDefaultSelectedKeys]="selectedKeys" - [nzDefaultExpandAll]="expandDefault"> + [nzDefaultExpandAll]="expandDefault" + > ` }) export class NzTestTreeOlderComponent implements OnInit { @ViewChild(NzTreeComponent) treeComponent: NzTreeComponent; - expandKeys = [ '1001', '10001' ]; - checkedKeys = [ '10001' ]; - selectedKeys = [ '10001', '100011' ]; + expandKeys = ['1001', '10001']; + checkedKeys = ['10001']; + selectedKeys = ['10001', '100011']; multiple = true; expandDefault = false; showExpand = true; @@ -794,32 +820,32 @@ export class NzTestTreeOlderComponent implements OnInit { ngOnInit(): void { this.modelNodes = [ { - title : 'root1', - key : '1001', + title: 'root1', + key: '1001', children: [ { - title : 'child1', - key : '10001', + title: 'child1', + key: '10001', children: [ { - title : 'child1.1', - key : '100011', + title: 'child1.1', + key: '100011', children: [] }, { - title : 'child1.2', - key : '100012', + title: 'child1.2', + key: '100012', disabled: true, children: [ { - title : 'grandchild1.2.1', - key : '1000121', + title: 'grandchild1.2.1', + key: '1000121', isLeaf: true }, { - title : 'grandchild1.2.2', - key : '1000122', - isLeaf : true, + title: 'grandchild1.2.2', + key: '1000122', + isLeaf: true, disableCheckbox: true } ] @@ -828,40 +854,40 @@ export class NzTestTreeOlderComponent implements OnInit { }, { title: 'child2', - key : '10002' + key: '10002' } ] }, { - title : 'root2', - key : '1002', + title: 'root2', + key: '1002', children: [ { - title : 'child2.1', - key : '10021', + title: 'child2.1', + key: '10021', disableCheckbox: true, - children : [ + children: [ { - title : 'grandchild2.1.1', - key : '100211', - isLeaf : true, + title: 'grandchild2.1.1', + key: '100211', + isLeaf: true, disableCheckbox: true }, { - title : 'grandchild2.1.2', - key : '1002112', - isLeaf : true, + title: 'grandchild2.1.2', + key: '1002112', + isLeaf: true, disableCheckbox: true } ] }, { - title : 'child2.2', - key : '10022', + title: 'child2.2', + key: '10022', children: [ { title: 'grandchild2.2.1', - key : '100221' + key: '100221' } ] } diff --git a/components/upload/demo/avatar.ts b/components/upload/demo/avatar.ts index 59ec20929c3..03774204f65 100644 --- a/components/upload/demo/avatar.ts +++ b/components/upload/demo/avatar.ts @@ -5,42 +5,44 @@ import { Observable, Observer } from 'rxjs'; @Component({ selector: 'nz-demo-upload-avatar', template: ` - - - -
    Upload
    -
    - -
    + + + +
    Upload
    +
    + +
    `, styles: [ ` - .avatar { - width: 128px; - height: 128px; - } - .upload-icon { - font-size: 32px; - color: #999; - } - .ant-upload-text { - margin-top: 8px; - color: #666; - } - ` + .avatar { + width: 128px; + height: 128px; + } + .upload-icon { + font-size: 32px; + color: #999; + } + .ant-upload-text { + margin-top: 8px; + color: #666; + } + ` ] }) export class NzDemoUploadAvatarComponent { loading = false; avatarUrl: string; - constructor(private msg: NzMessageService) { } + constructor(private msg: NzMessageService) {} beforeUpload = (file: File) => { return new Observable((observer: Observer) => { @@ -68,7 +70,7 @@ export class NzDemoUploadAvatarComponent { observer.complete(); }); }); - } + }; private getBase64(img: File, callback: (img: string) => void): void { const reader = new FileReader(); diff --git a/components/upload/demo/basic.ts b/components/upload/demo/basic.ts index adfff456893..3eb46184ed5 100644 --- a/components/upload/demo/basic.ts +++ b/components/upload/demo/basic.ts @@ -3,12 +3,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-upload-basic', template: ` - - - + + + ` }) export class NzDemoUploadBasicComponent {} diff --git a/components/upload/demo/custom-request.ts b/components/upload/demo/custom-request.ts index b44d515054a..5687ee09a6a 100644 --- a/components/upload/demo/custom-request.ts +++ b/components/upload/demo/custom-request.ts @@ -6,17 +6,12 @@ import { forkJoin } from 'rxjs'; @Component({ selector: 'nz-demo-upload-custom-request', template: ` - - - + + + ` }) export class NzDemoUploadCustomRequestComponent { - constructor(private http: HttpClient) {} customReq = (item: UploadXHRArgs) => { @@ -26,55 +21,63 @@ export class NzDemoUploadCustomRequestComponent { formData.append('file', item.file as any); formData.append('id', '1000'); const req = new HttpRequest('POST', item.action!, formData, { - reportProgress : true, + reportProgress: true, withCredentials: true }); // 始终返回一个 `Subscription` 对象,nz-upload 会在适当时机自动取消订阅 - return this.http.request(req).subscribe((event: HttpEvent<{}>) => { - if (event.type === HttpEventType.UploadProgress) { - if (event.total! > 0) { - // tslint:disable-next-line:no-any - (event as any).percent = event.loaded / event.total! * 100; + return this.http.request(req).subscribe( + (event: HttpEvent<{}>) => { + if (event.type === HttpEventType.UploadProgress) { + if (event.total! > 0) { + // tslint:disable-next-line:no-any + (event as any).percent = (event.loaded / event.total!) * 100; + } + // 处理上传进度条,必须指定 `percent` 属性来表示进度 + item.onProgress!(event, item.file!); + } else if (event instanceof HttpResponse) { + // 处理成功 + item.onSuccess!(event.body, item.file!, event); } - // 处理上传进度条,必须指定 `percent` 属性来表示进度 - item.onProgress!(event, item.file!); - } else if (event instanceof HttpResponse) { - // 处理成功 - item.onSuccess!(event.body, item.file!, event); + }, + err => { + // 处理失败 + item.onError!(err, item.file!); } - }, (err) => { - // 处理失败 - item.onError!(err, item.file!); - }); - } + ); + }; // 一个简单的分片上传 customBigReq = (item: UploadXHRArgs) => { const size = item.file.size; - const chunkSize = parseInt((size / 3) + '', 10); + const chunkSize = parseInt(size / 3 + '', 10); const maxChunk = Math.ceil(size / chunkSize); - const reqs = Array(maxChunk).fill(0).map((_: {}, index: number) => { - const start = index * chunkSize; - let end = start + chunkSize; - if (size - end < 0) { - end = size; - } - const formData = new FormData(); - formData.append('file', item.file.slice(start, end)); - formData.append('start', start.toString()); - formData.append('end', end.toString()); - formData.append('index', index.toString()); - const req = new HttpRequest('POST', item.action!, formData, { - withCredentials: true + const reqs = Array(maxChunk) + .fill(0) + .map((_: {}, index: number) => { + const start = index * chunkSize; + let end = start + chunkSize; + if (size - end < 0) { + end = size; + } + const formData = new FormData(); + formData.append('file', item.file.slice(start, end)); + formData.append('start', start.toString()); + formData.append('end', end.toString()); + formData.append('index', index.toString()); + const req = new HttpRequest('POST', item.action!, formData, { + withCredentials: true + }); + return this.http.request(req); }); - return this.http.request(req); - }); - return forkJoin(...reqs).subscribe(() => { - // 处理成功 - item.onSuccess!({}, item.file!, event); - }, (err) => { - // 处理失败 - item.onError!(err, item.file!); - }); - } + return forkJoin(...reqs).subscribe( + () => { + // 处理成功 + item.onSuccess!({}, item.file!, event); + }, + err => { + // 处理失败 + item.onError!(err, item.file!); + } + ); + }; } diff --git a/components/upload/demo/directory.ts b/components/upload/demo/directory.ts index 81294eefbeb..7d5bd48964c 100644 --- a/components/upload/demo/directory.ts +++ b/components/upload/demo/directory.ts @@ -3,13 +3,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-upload-directory', template: ` - - - + + + ` }) export class NzDemoUploadDirectoryComponent {} diff --git a/components/upload/demo/drag.ts b/components/upload/demo/drag.ts index c7beccfb439..dd3af0e5a95 100644 --- a/components/upload/demo/drag.ts +++ b/components/upload/demo/drag.ts @@ -4,24 +4,27 @@ import { NzMessageService } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-upload-drag', template: ` - -

    - -

    -

    Click or drag file to this area to upload

    -

    Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files

    -
    + +

    + +

    +

    Click or drag file to this area to upload

    +

    + Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files +

    +
    ` }) export class NzDemoUploadDragComponent { constructor(private msg: NzMessageService) {} // tslint:disable-next-line:no-any - handleChange({ file, fileList }: { [ key: string ]: any }): void { + handleChange({ file, fileList }: { [key: string]: any }): void { const status = file.status; if (status !== 'uploading') { console.log(file, fileList); diff --git a/components/upload/demo/file-list.ts b/components/upload/demo/file-list.ts index f3d22a3079a..37e4fe1a7b6 100644 --- a/components/upload/demo/file-list.ts +++ b/components/upload/demo/file-list.ts @@ -3,13 +3,9 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-upload-file-list', template: ` - - - + + + ` }) export class NzDemoUploadFileListComponent { diff --git a/components/upload/demo/filter.ts b/components/upload/demo/filter.ts index 82360bc909e..68e209eecda 100644 --- a/components/upload/demo/filter.ts +++ b/components/upload/demo/filter.ts @@ -5,27 +5,25 @@ import { Observable, Observer } from 'rxjs'; @Component({ selector: 'nz-demo-upload-filter', template: ` - - - + + + ` }) export class NzDemoUploadFilterComponent { - constructor(private msg: NzMessageService) {} filters: UploadFilter[] = [ { name: 'type', - fn : (fileList: UploadFile[]) => { + fn: (fileList: UploadFile[]) => { const filterFiles = fileList.filter(w => ~['image/png'].indexOf(w.type)); if (filterFiles.length !== fileList.length) { this.msg.error(`包含文件格式不正确,只支持 png 格式`); diff --git a/components/upload/demo/manually.ts b/components/upload/demo/manually.ts index 6a2048bd866..2f31131d955 100644 --- a/components/upload/demo/manually.ts +++ b/components/upload/demo/manually.ts @@ -6,16 +6,19 @@ import { filter } from 'rxjs/operators'; @Component({ selector: 'nz-demo-upload-manually', template: ` - - + + - - ` }) export class NzDemoUploadManuallyComponent { @@ -27,7 +30,7 @@ export class NzDemoUploadManuallyComponent { beforeUpload = (file: UploadFile): boolean => { this.fileList = this.fileList.concat(file); return false; - } + }; handleUpload(): void { const formData = new FormData(); diff --git a/components/upload/demo/picture-card.ts b/components/upload/demo/picture-card.ts index 73c8f5b808a..88d102cca52 100644 --- a/components/upload/demo/picture-card.ts +++ b/components/upload/demo/picture-card.ts @@ -4,41 +4,47 @@ import { UploadFile } from 'ng-zorro-antd'; @Component({ selector: 'nz-demo-upload-picture-card', template: ` -
    - +
    +
    Upload
    -
    - - - - - -
    +
    + + + + + +
    `, styles: [ ` - i[nz-icon] { - font-size: 32px; - color: #999; - } - .ant-upload-text { - margin-top: 8px; - color: #666; - } - ` + i[nz-icon] { + font-size: 32px; + color: #999; + } + .ant-upload-text { + margin-top: 8px; + color: #666; + } + ` ] }) export class NzDemoUploadPictureCardComponent { showUploadList = { showPreviewIcon: true, - showRemoveIcon : true, + showRemoveIcon: true, hidePreviewIconInNonImage: true }; fileList = [ @@ -57,5 +63,5 @@ export class NzDemoUploadPictureCardComponent { handlePreview = (file: UploadFile) => { this.previewImage = file.url || file.thumbUrl; this.previewVisible = true; - } + }; } diff --git a/components/upload/demo/picture-style.ts b/components/upload/demo/picture-style.ts index 446193d791d..dd641024d0a 100644 --- a/components/upload/demo/picture-style.ts +++ b/components/upload/demo/picture-style.ts @@ -3,36 +3,33 @@ import { Component } from '@angular/core'; @Component({ selector: 'nz-demo-upload-picture-style', template: ` -
    - - - -
    -

    -
    - - - -
    +
    + + + +
    +

    +
    + + + +
    `, styles: [ ` - :host ::ng-deep .upload-list-inline .ant-upload-list-item { - float: left; - width: 200px; - margin-right: 8px; - } - ` + :host ::ng-deep .upload-list-inline .ant-upload-list-item { + float: left; + width: 200px; + margin-right: 8px; + } + ` ] }) export class NzDemoUploadPictureStyleComponent { diff --git a/components/upload/interface.ts b/components/upload/interface.ts index 3284b5799e9..7c5ae54e524 100644 --- a/components/upload/interface.ts +++ b/components/upload/interface.ts @@ -29,7 +29,7 @@ export interface UploadFile { linkProps?: { download: string }; type: string; - [ key: string ]: any; + [key: string]: any; } export interface UploadChangeParam { diff --git a/components/upload/nz-upload-btn.component.ts b/components/upload/nz-upload-btn.component.ts index b8b16452e99..1978e90e9d5 100644 --- a/components/upload/nz-upload-btn.component.ts +++ b/components/upload/nz-upload-btn.component.ts @@ -1,12 +1,5 @@ import { ENTER } from '@angular/cdk/keycodes'; -import { - HttpClient, - HttpEvent, - HttpEventType, - HttpHeaders, - HttpRequest, - HttpResponse -} from '@angular/common/http'; +import { HttpClient, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http'; import { Component, ElementRef, @@ -27,18 +20,18 @@ import { NzUpdateHostClassService } from '../core/services/update-host-class.ser import { UploadFile, UploadXHRArgs, ZipButtonOptions } from './interface'; @Component({ - selector : '[nz-upload-btn]', - templateUrl : './nz-upload-btn.component.html', - host : { + selector: '[nz-upload-btn]', + templateUrl: './nz-upload-btn.component.html', + host: { '[attr.tabindex]': '"0"', - '[attr.role]' : '"button"' + '[attr.role]': '"button"' }, - providers : [ NzUpdateHostClassService ], + providers: [NzUpdateHostClassService], preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None + encapsulation: ViewEncapsulation.None }) export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { - reqs: { [ key: string ]: Subscription } = {}; + reqs: { [key: string]: Subscription } = {}; private inited = false; private destroy = false; @@ -58,7 +51,7 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { (this.file.nativeElement as HTMLInputElement).click(); } - @HostListener('keydown', [ '$event' ]) + @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent): void { if (this.options.disabled) { return; @@ -68,8 +61,8 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { } } - @HostListener('drop', [ '$event' ]) - @HostListener('dragover', [ '$event' ]) + @HostListener('drop', ['$event']) + @HostListener('dragover', ['$event']) onFileDrop(e: DragEvent): void { if (this.options.disabled || e.type === 'dragover') { e.preventDefault(); @@ -78,9 +71,9 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { if (this.options.directory) { this.traverseFileTree(e.dataTransfer!.items); } else { - const files: File[] = Array.prototype.slice.call(e.dataTransfer!.files).filter( - (file: File) => this.attrAccept(file, this.options.accept) - ); + const files: File[] = Array.prototype.slice + .call(e.dataTransfer!.files) + .filter((file: File) => this.attrAccept(file, this.options.accept)); if (files.length) { this.uploadFiles(files); } @@ -104,13 +97,14 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { if (item.isFile) { item.file((file: File) => { if (this.attrAccept(file, this.options.accept)) { - this.uploadFiles([ file ]); + this.uploadFiles([file]); } }); } else if (item.isDirectory) { const dirReader = item.createReader(); - dirReader.readEntries((entries: any) => { // tslint:disable-line:no-any + // tslint:disable-next-line:no-any + dirReader.readEntries((entries: any) => { for (const entrieItem of entries) { _traverseFileTree(entrieItem, `${path}${item.name}/`); } @@ -133,7 +127,11 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { return acceptedFilesArray.some(type => { const validType = type.trim(); if (validType.charAt(0) === '.') { - return fileName.toLowerCase().indexOf(validType.toLowerCase(), fileName.toLowerCase().length - validType.toLowerCase().length) !== -1; + return ( + fileName + .toLowerCase() + .indexOf(validType.toLowerCase(), fileName.toLowerCase().length - validType.toLowerCase().length) !== -1 + ); } else if (/\/\*$/.test(validType)) { // This is something like a image/* mime type return baseMimeType === validType.replace(/\/.*$/, ''); @@ -146,7 +144,9 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { private attachUid(file: UploadFile): UploadFile { if (!file.uid) { - file.uid = Math.random().toString(36).substring(2); + file.uid = Math.random() + .toString(36) + .substring(2); } return file; } @@ -155,20 +155,25 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { let filters$: Observable = of(Array.prototype.slice.call(fileList)); if (this.options.filters) { this.options.filters.forEach(f => { - filters$ = filters$.pipe(switchMap(list => { - const fnRes = f.fn(list); - return fnRes instanceof Observable ? fnRes : of(fnRes); - })); + filters$ = filters$.pipe( + switchMap(list => { + const fnRes = f.fn(list); + return fnRes instanceof Observable ? fnRes : of(fnRes); + }) + ); }); } - filters$.subscribe(list => { - list.forEach((file: UploadFile) => { - this.attachUid(file); - this.upload(file, list); - }); - }, e => { - console.warn(`Unhandled upload filter error`, e); - }); + filters$.subscribe( + list => { + list.forEach((file: UploadFile) => { + this.attachUid(file); + this.upload(file, list); + }); + }, + e => { + console.warn(`Unhandled upload filter error`, e); + } + ); } private upload(file: UploadFile, fileList: UploadFile[]): void { @@ -177,17 +182,20 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { } const before = this.options.beforeUpload(file, fileList); if (before instanceof Observable) { - before.subscribe((processedFile: UploadFile) => { - const processedFileType = Object.prototype.toString.call(processedFile); - if (processedFileType === '[object File]' || processedFileType === '[object Blob]') { - this.attachUid(processedFile); - this.post(processedFile); - } else if (typeof processedFile === 'boolean' && processedFile !== false) { - this.post(file); + before.subscribe( + (processedFile: UploadFile) => { + const processedFileType = Object.prototype.toString.call(processedFile); + if (processedFileType === '[object File]' || processedFileType === '[object Blob]') { + this.attachUid(processedFile); + this.post(processedFile); + } else if (typeof processedFile === 'boolean' && processedFile !== false) { + this.post(file); + } + }, + e => { + console.warn(`Unhandled upload beforeUpload error`, e); } - }, e => { - console.warn(`Unhandled upload beforeUpload error`, e); - }); + ); } else if (before !== false) { return this.post(file); } @@ -207,20 +215,22 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { headers = (headers as (file: UploadFile) => {})(file); } const args: UploadXHRArgs = { - action : opt.action, - name : opt.name, + action: opt.action, + name: opt.name, headers, file, data, withCredentials: opt.withCredentials, - onProgress : opt.onProgress ? e => { - opt.onProgress!(e, file); - } : undefined, - onSuccess : (ret, xhr) => { + onProgress: opt.onProgress + ? e => { + opt.onProgress!(e, file); + } + : undefined, + onSuccess: (ret, xhr) => { this.clean(uid); opt.onSuccess!(ret, file, xhr); }, - onError : (xhr) => { + onError: xhr => { this.clean(uid); opt.onError!(xhr, file); } @@ -229,7 +239,7 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { if (!(req$ instanceof Subscription)) { console.warn(`Must return Subscription type in '[nzCustomRequest]' property`); } - this.reqs[ uid ] = req$; + this.reqs[uid] = req$; opt.onStart!(file); } @@ -239,51 +249,54 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { formData.append(args.name!, args.file as any); if (args.data) { Object.keys(args.data).map(key => { - formData.append(key, args.data![ key ]); + formData.append(key, args.data![key]); }); } if (!args.headers) { args.headers = {}; } - if (args.headers[ 'X-Requested-With' ] !== null) { - args.headers[ 'X-Requested-With' ] = `XMLHttpRequest`; + if (args.headers['X-Requested-With'] !== null) { + args.headers['X-Requested-With'] = `XMLHttpRequest`; } else { - delete args.headers[ 'X-Requested-With' ]; + delete args.headers['X-Requested-With']; } const req = new HttpRequest('POST', args.action!, formData, { - reportProgress : true, + reportProgress: true, withCredentials: args.withCredentials, - headers : new HttpHeaders(args.headers) + headers: new HttpHeaders(args.headers) }); - return this.http.request(req).subscribe((event: HttpEvent<{}>) => { - if (event.type === HttpEventType.UploadProgress) { - if (event.total! > 0) { - // tslint:disable-next-line:no-any - (event as any).percent = event.loaded / event.total! * 100; + return this.http.request(req).subscribe( + (event: HttpEvent<{}>) => { + if (event.type === HttpEventType.UploadProgress) { + if (event.total! > 0) { + // tslint:disable-next-line:no-any + (event as any).percent = (event.loaded / event.total!) * 100; + } + args.onProgress!(event, args.file); + } else if (event instanceof HttpResponse) { + args.onSuccess!(event.body, args.file, event); } - args.onProgress!(event, args.file); - } else if (event instanceof HttpResponse) { - args.onSuccess!(event.body, args.file, event); + }, + err => { + this.abort(args.file); + args.onError!(err, args.file); } - }, (err) => { - this.abort(args.file); - args.onError!(err, args.file); - }); + ); } private clean(uid: string): void { - const req$ = this.reqs[ uid ]; + const req$ = this.reqs[uid]; if (req$ instanceof Subscription) { req$.unsubscribe(); } - delete this.reqs[ uid ]; + delete this.reqs[uid]; } abort(file?: UploadFile): void { if (file) { this.clean(file && file.uid); } else { - Object.keys(this.reqs).forEach((uid) => this.clean(uid)); + Object.keys(this.reqs).forEach(uid => this.clean(uid)); } } @@ -293,8 +306,8 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { private setClassMap(): void { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-disabled` ]: this.options.disabled, + [this.prefixCls]: true, + [`${this.prefixCls}-disabled`]: this.options.disabled, ...this.classes }; this.updateHostClassService.updateHostClass(this.el.nativeElement, classMap); @@ -302,7 +315,11 @@ export class NzUploadBtnComponent implements OnInit, OnChanges, OnDestroy { // #endregion - constructor(@Optional() private http: HttpClient, private el: ElementRef, private updateHostClassService: NzUpdateHostClassService) { + constructor( + @Optional() private http: HttpClient, + private el: ElementRef, + private updateHostClassService: NzUpdateHostClassService + ) { if (!http) { throw new Error(`Not found 'HttpClient', You can import 'HttpClientModule' in your root module.`); } diff --git a/components/upload/nz-upload-list.component.ts b/components/upload/nz-upload-list.component.ts index a430041a203..73aedee5276 100644 --- a/components/upload/nz-upload-list.component.ts +++ b/components/upload/nz-upload-list.component.ts @@ -1,28 +1,34 @@ import { animate, style, transition, trigger } from '@angular/animations'; -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, OnChanges, ViewEncapsulation } from '@angular/core'; +import { + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + ElementRef, + Input, + OnChanges, + ViewEncapsulation +} from '@angular/core'; import { NzUpdateHostClassService } from '../core/services/update-host-class.service'; import { ShowUploadListInterface, UploadFile, UploadListType } from './interface'; @Component({ - selector : 'nz-upload-list', - templateUrl : './nz-upload-list.component.html', - providers : [ NzUpdateHostClassService ], - animations : [ + selector: 'nz-upload-list', + templateUrl: './nz-upload-list.component.html', + providers: [NzUpdateHostClassService], + animations: [ trigger('itemState', [ transition(':enter', [ style({ height: '0', width: '0', opacity: 0 }), animate(150, style({ height: '*', width: '*', opacity: 1 })) ]), - transition(':leave', [ - animate(150, style({ height: '0', width: '0', opacity: 0 })) - ]) + transition(':leave', [animate(150, style({ height: '0', width: '0', opacity: 0 }))]) ]) ], preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzUploadListComponent implements OnChanges { private imageTypes = ['image', 'webp', 'png', 'svg', 'gif', 'jpg', 'jpeg', 'bmp']; @@ -59,8 +65,8 @@ export class NzUploadListComponent implements OnChanges { private setClassMap(): void { const classMap = { - [ this.prefixCls ] : true, - [ `${this.prefixCls}-${this.listType}` ]: true + [this.prefixCls]: true, + [`${this.prefixCls}-${this.listType}`]: true }; this.updateHostClassService.updateHostClass(this.el.nativeElement, classMap); } @@ -117,7 +123,7 @@ export class NzUploadListComponent implements OnChanges { !win.FileReader || !win.File ) { - return ; + return; } this.items .filter(file => file.originFileObj instanceof File && file.thumbUrl === undefined) @@ -157,8 +163,11 @@ export class NzUploadListComponent implements OnChanges { // #endregion - constructor(private el: ElementRef, private cdr: ChangeDetectorRef, private updateHostClassService: NzUpdateHostClassService) { - } + constructor( + private el: ElementRef, + private cdr: ChangeDetectorRef, + private updateHostClassService: NzUpdateHostClassService + ) {} detectChanges(): void { this.cdr.detectChanges(); diff --git a/components/upload/nz-upload.component.ts b/components/upload/nz-upload.component.ts index d185a176f8d..8dbb6ffff65 100644 --- a/components/upload/nz-upload.component.ts +++ b/components/upload/nz-upload.component.ts @@ -33,11 +33,11 @@ import { NzUploadBtnComponent } from './nz-upload-btn.component'; import { NzUploadListComponent } from './nz-upload-list.component'; @Component({ - selector : 'nz-upload', - templateUrl : './nz-upload.component.html', + selector: 'nz-upload', + templateUrl: './nz-upload.component.html', preserveWhitespaces: false, - encapsulation : ViewEncapsulation.None, - changeDetection : ChangeDetectionStrategy.OnPush + encapsulation: ViewEncapsulation.None, + changeDetection: ChangeDetectionStrategy.OnPush }) export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { private i18n$: Subscription; @@ -94,7 +94,7 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { if (typeof this.nzShowUploadList === 'boolean' && this.nzShowUploadList) { this.nzShowUploadList = { showPreviewIcon: true, - showRemoveIcon : true, + showRemoveIcon: true, hidePreviewIconInNonImage: false }; } @@ -103,69 +103,68 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { if (this.nzMultiple && this.nzLimit > 0 && filters.findIndex(w => w.name === 'limit') === -1) { filters.push({ name: 'limit', - fn : (fileList: UploadFile[]) => fileList.slice(-this.nzLimit) + fn: (fileList: UploadFile[]) => fileList.slice(-this.nzLimit) }); } if (this.nzSize > 0 && filters.findIndex(w => w.name === 'size') === -1) { filters.push({ name: 'size', - fn : (fileList: UploadFile[]) => fileList.filter(w => (w.size / 1024) <= this.nzSize) + fn: (fileList: UploadFile[]) => fileList.filter(w => w.size / 1024 <= this.nzSize) }); } if (this.nzFileType && this.nzFileType.length > 0 && filters.findIndex(w => w.name === 'type') === -1) { const types = this.nzFileType.split(','); filters.push({ name: 'type', - fn : (fileList: UploadFile[]) => fileList.filter(w => ~types.indexOf(w.type)) + fn: (fileList: UploadFile[]) => fileList.filter(w => ~types.indexOf(w.type)) }); } this._btnOptions = { - disabled : this.nzDisabled, - accept : this.nzAccept, - action : this.nzAction, - directory : this.nzDirectory, - openFileDialogOnClick : this.nzOpenFileDialogOnClick, - beforeUpload : this.nzBeforeUpload, - customRequest : this.nzCustomRequest, - data : this.nzData, - headers : this.nzHeaders, - name : this.nzName, - multiple : this.nzMultiple, + disabled: this.nzDisabled, + accept: this.nzAccept, + action: this.nzAction, + directory: this.nzDirectory, + openFileDialogOnClick: this.nzOpenFileDialogOnClick, + beforeUpload: this.nzBeforeUpload, + customRequest: this.nzCustomRequest, + data: this.nzData, + headers: this.nzHeaders, + name: this.nzName, + multiple: this.nzMultiple, withCredentials: this.nzWithCredentials, filters, - onStart : this.onStart, - onProgress : this.onProgress, - onSuccess : this.onSuccess, - onError : this.onError + onStart: this.onStart, + onProgress: this.onProgress, + onSuccess: this.onSuccess, + onError: this.onError }; return this; } // #endregion - constructor(private cdr: ChangeDetectorRef, private i18n: NzI18nService) { - } + constructor(private cdr: ChangeDetectorRef, private i18n: NzI18nService) {} // #region upload private fileToObject(file: UploadFile): UploadFile { return { - lastModified : file.lastModified, + lastModified: file.lastModified, lastModifiedDate: file.lastModifiedDate, - name : file.filename || file.name, - size : file.size, - type : file.type, - uid : file.uid, - response : file.response, - error : file.error, - percent : 0, + name: file.filename || file.name, + size: file.size, + type: file.type, + uid: file.uid, + response: file.response, + error: file.error, + percent: 0, // tslint:disable-next-line:no-any - originFileObj : file as any + originFileObj: file as any }; } private getFileItem(file: UploadFile, fileList: UploadFile[]): UploadFile { - return fileList.filter(item => item.uid === file.uid)[ 0 ]; + return fileList.filter(item => item.uid === file.uid)[0]; } private removeFileItem(file: UploadFile, fileList: UploadFile[]): UploadFile[] { @@ -173,9 +172,9 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { } private genErr(file: UploadFile): string { - return file.response && typeof file.response === 'string' ? - file.response : - (file.error && file.error.statusText) || this.locale.uploadError; + return file.response && typeof file.response === 'string' + ? file.response + : (file.error && file.error.statusText) || this.locale.uploadError; } private onStart = (file: UploadFile): void => { @@ -188,20 +187,20 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { this.nzFileListChange.emit(this.nzFileList); this.nzChange.emit({ file: targetItem, fileList: this.nzFileList, type: 'start' }); this.detectChangesList(); - } + }; private onProgress = (e: { percent: number }, file: UploadFile): void => { const fileList = this.nzFileList; const targetItem = this.getFileItem(file, fileList); targetItem.percent = e.percent; this.nzChange.emit({ - event : e, - file : { ...targetItem }, + event: e, + file: { ...targetItem }, fileList: this.nzFileList, - type : 'progress' + type: 'progress' }); this.detectChangesList(); - } + }; private onSuccess = (res: {}, file: UploadFile): void => { const fileList = this.nzFileList; @@ -214,7 +213,7 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { type: 'success' }); this.detectChangesList(); - } + }; private onError = (err: {}, file: UploadFile): void => { const fileList = this.nzFileList; @@ -228,7 +227,7 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { type: 'error' }); this.detectChangesList(); - } + }; // #endregion @@ -256,21 +255,19 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { onRemove = (file: UploadFile): void => { this.uploadComp.abort(file); file.status = 'removed'; - const fnRes = typeof this.nzRemove === 'function' ? - this.nzRemove(file) : this.nzRemove == null ? true : this.nzRemove; - (fnRes instanceof Observable ? fnRes : of(fnRes)) - .pipe(filter((res: boolean) => res)) - .subscribe(() => { + const fnRes = + typeof this.nzRemove === 'function' ? this.nzRemove(file) : this.nzRemove == null ? true : this.nzRemove; + (fnRes instanceof Observable ? fnRes : of(fnRes)).pipe(filter((res: boolean) => res)).subscribe(() => { this.nzFileList = this.removeFileItem(file, this.nzFileList); this.nzChange.emit({ file, fileList: this.nzFileList, - type : 'removed' + type: 'removed' }); this.nzFileListChange.emit(this.nzFileList); this.cdr.detectChanges(); }); - } + }; // #endregion @@ -289,16 +286,14 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { subCls.push(`${this.prefixCls}-drag-hover`); } } else { - subCls = [ - `${this.prefixCls}-select-${this.nzListType}` - ]; + subCls = [`${this.prefixCls}-select-${this.nzListType}`]; } this.classList = [ this.prefixCls, `${this.prefixCls}-${this.nzType}`, ...subCls, - this.nzDisabled && `${this.prefixCls}-disabled` || '' + (this.nzDisabled && `${this.prefixCls}-disabled`) || '' ].filter(item => !!item); this.cdr.detectChanges(); @@ -315,7 +310,7 @@ export class NzUploadComponent implements OnInit, OnChanges, OnDestroy { ngOnChanges(changes: { [P in keyof this]?: SimpleChange } & SimpleChanges): void { if (changes.nzFileList) { - (this.nzFileList || []).forEach(file => file.message = this.genErr(file)); + (this.nzFileList || []).forEach(file => (file.message = this.genErr(file))); } this.zipOptions().setClassMap(); } diff --git a/components/upload/nz-upload.module.ts b/components/upload/nz-upload.module.ts index e25becd4c4c..cb0078f63aa 100644 --- a/components/upload/nz-upload.module.ts +++ b/components/upload/nz-upload.module.ts @@ -12,8 +12,8 @@ import { NzUploadListComponent } from './nz-upload-list.component'; import { NzUploadComponent } from './nz-upload.component'; @NgModule({ - imports: [CommonModule, FormsModule, NzToolTipModule, NzProgressModule, NzI18nModule, NzIconModule], + imports: [CommonModule, FormsModule, NzToolTipModule, NzProgressModule, NzI18nModule, NzIconModule], declarations: [NzUploadComponent, NzUploadBtnComponent, NzUploadListComponent], - exports: [NzUploadComponent] + exports: [NzUploadComponent] }) -export class NzUploadModule { } +export class NzUploadModule {} diff --git a/components/upload/upload.spec.ts b/components/upload/upload.spec.ts index eb87640ebcc..7632713817f 100644 --- a/components/upload/upload.spec.ts +++ b/components/upload/upload.spec.ts @@ -29,20 +29,26 @@ import { NzUploadBtnComponent } from './nz-upload-btn.component'; import { NzUploadListComponent } from './nz-upload-list.component'; import { NzUploadComponent } from './nz-upload.component'; -const FILECONTENT = [ `iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==` ]; +const FILECONTENT = [ + `iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==` +]; const FILE = new File(FILECONTENT, ''); const PNGSMALL = { target: { - files: [ new File(FILECONTENT, 'test.png', { - type: 'image/png' - }) ] + files: [ + new File(FILECONTENT, 'test.png', { + type: 'image/png' + }) + ] } }; const JPGSMALL = { target: { - files: [ new File(FILECONTENT, 'test.jpg', { - type: 'image/jpg' - }) ] + files: [ + new File(FILECONTENT, 'test.jpg', { + type: 'image/jpg' + }) + ] } }; const LARGEFILE = { @@ -59,11 +65,10 @@ class Item { } describe('upload', () => { - it('should be throw error when not import HttpClient module', () => { expect(() => { TestBed.configureTestingModule({ - declarations: [ NzUploadBtnComponent, TestUploadBtnComponent ] + declarations: [NzUploadBtnComponent, TestUploadBtnComponent] }).createComponent(TestUploadBtnComponent); }).toThrow(); }); @@ -77,8 +82,17 @@ describe('upload', () => { let httpMock: HttpTestingController; beforeEach(() => { injector = TestBed.configureTestingModule({ - imports : [ NoopAnimationsModule, HttpClientTestingModule, CommonModule, FormsModule, NzToolTipModule, NzProgressModule, NzI18nModule, NzIconTestModule ], - declarations: [ NzUploadComponent, NzUploadListComponent, TestUploadComponent, NzUploadBtnComponent ] + imports: [ + NoopAnimationsModule, + HttpClientTestingModule, + CommonModule, + FormsModule, + NzToolTipModule, + NzProgressModule, + NzI18nModule, + NzIconTestModule + ], + declarations: [NzUploadComponent, NzUploadListComponent, TestUploadComponent, NzUploadBtnComponent] }); fixture = TestBed.createComponent(TestUploadComponent); dl = fixture.debugElement; @@ -89,7 +103,6 @@ describe('upload', () => { }); describe('[default]', () => { - it('should be upload a file', () => { expect(instance._nzChange).toBeUndefined(); pageObject.postFile(FILE); @@ -127,11 +140,7 @@ describe('upload', () => { instance.nzMultiple = true; fixture.detectChanges(); expect(instance._beforeUploadList.length).toBe(0); - pageObject.postFile([ - ...PNGSMALL.target.files, - ...PNGSMALL.target.files, - ...PNGSMALL.target.files - ]); + pageObject.postFile([...PNGSMALL.target.files, ...PNGSMALL.target.files, ...PNGSMALL.target.files]); expect(instance._beforeUploadList.length).toBe(instance.nzLimit); }); @@ -163,13 +172,15 @@ describe('upload', () => { }); it('should be removed via list', () => { - instance.nzFileList = [ { - uid : 1, - name : 'xxx.png', - status : 'done', - response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/xxx.png' - } as any ]; + instance.nzFileList = [ + { + uid: 1, + name: 'xxx.png', + status: 'done', + response: 'Server Error 500', // custom error message to show + url: 'http://www.baidu.com/xxx.png' + } as any + ]; fixture.detectChanges(); pageObject.expectLength(1); pageObject.getByCss('.anticon-close').nativeElement.click(); @@ -188,23 +199,27 @@ describe('upload', () => { it('should be show uploading status when via drag', () => { instance.nzType = 'drag'; - instance.nzFileList = [ { - uid : 1, - name : 'xxx.png', - status: 'uploading' - } as any ]; + instance.nzFileList = [ + { + uid: 1, + name: 'xxx.png', + status: 'uploading' + } as any + ]; fixture.detectChanges(); expect(pageObject.getByCss('.ant-upload-drag-uploading') != null).toBe(true); }); it('#i18n', () => { - instance.nzFileList = [ { - uid : 1, - name : 'xxx.png', - status : 'done', - response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/xxx.png' - } as any ]; + instance.nzFileList = [ + { + uid: 1, + name: 'xxx.png', + status: 'done', + response: 'Server Error 500', // custom error message to show + url: 'http://www.baidu.com/xxx.png' + } as any + ]; fixture.detectChanges(); injector.get(NzI18nService).setLocale(en_US); fixture.detectChanges(); @@ -238,9 +253,7 @@ describe('upload', () => { }); it('should comst fileter', () => { - instance.nzFilter = [ - { name: 'custom', fn: () => [] } - ]; + instance.nzFilter = [{ name: 'custom', fn: () => [] }]; fixture.detectChanges(); expect(instance._beforeUploadList.length).toBe(0); pageObject.postLarge(); @@ -347,7 +360,7 @@ describe('upload', () => { let ret = false; instance.beforeUpload = (): Observable => { ret = true; - return of(new Blob([ JSON.stringify(1, null, 2) ], { type: 'application/json' })); + return of(new Blob([JSON.stringify(1, null, 2)], { type: 'application/json' })); }; fixture.detectChanges(); pageObject.postSmall(); @@ -364,7 +377,7 @@ describe('upload', () => { }); it('should be console.warn error', () => { let warnMsg = ''; - console.warn = jasmine.createSpy().and.callFake((res: string) => warnMsg = res); + console.warn = jasmine.createSpy().and.callFake((res: string) => (warnMsg = res)); expect(instance._nzChange).toBeUndefined(); instance.beforeUpload = (): Observable => { return throwError(''); @@ -383,16 +396,12 @@ describe('upload', () => { instance.nzFilter = [ { name: 'limit', - fn : (fileList: UploadFile[]) => fileList.slice(-instance.nzLimit) + fn: (fileList: UploadFile[]) => fileList.slice(-instance.nzLimit) } ]; fixture.detectChanges(); expect(instance._beforeUploadList.length).toBe(0); - pageObject.postFile([ - ...PNGSMALL.target.files, - ...PNGSMALL.target.files, - ...PNGSMALL.target.files - ]); + pageObject.postFile([...PNGSMALL.target.files, ...PNGSMALL.target.files, ...PNGSMALL.target.files]); expect(instance._beforeUploadList.length).toBe(instance.nzLimit); }); it('shoule be custom size', () => { @@ -400,7 +409,7 @@ describe('upload', () => { instance.nzFilter = [ { name: 'size', - fn : (fileList: UploadFile[]) => fileList.filter(w => (w.size / 1024) <= instance.nzSize) + fn: (fileList: UploadFile[]) => fileList.filter(w => w.size / 1024 <= instance.nzSize) } ]; fixture.detectChanges(); @@ -413,7 +422,7 @@ describe('upload', () => { instance.nzFilter = [ { name: 'type', - fn : (fileList: UploadFile[]) => fileList.filter(w => ~[ instance.nzFileType ].indexOf(w.type)) + fn: (fileList: UploadFile[]) => fileList.filter(w => ~[instance.nzFileType].indexOf(w.type)) } ]; fixture.detectChanges(); @@ -426,7 +435,7 @@ describe('upload', () => { instance.nzFilter = [ { name: 'f1', - fn : (fileList: UploadFile[]) => { + fn: (fileList: UploadFile[]) => { return new Observable((observer: Observer) => { observer.next(fileList.slice(1)); observer.complete(); @@ -435,7 +444,7 @@ describe('upload', () => { }, { name: 'f2', - fn : (fileList: UploadFile[]) => { + fn: (fileList: UploadFile[]) => { return new Observable((observer: Observer) => { observer.next(fileList.slice(1)); observer.complete(); @@ -445,20 +454,16 @@ describe('upload', () => { ]; fixture.detectChanges(); expect(instance._beforeUploadList.length).toBe(0); - pageObject.postFile([ - ...PNGSMALL.target.files, - ...PNGSMALL.target.files, - ...PNGSMALL.target.files - ]); + pageObject.postFile([...PNGSMALL.target.files, ...PNGSMALL.target.files, ...PNGSMALL.target.files]); expect(instance._beforeUploadList.length).toBe(1); }); it('should be console.warn error', () => { let warnMsg = ''; - console.warn = jasmine.createSpy().and.callFake((res: string) => warnMsg = res); + console.warn = jasmine.createSpy().and.callFake((res: string) => (warnMsg = res)); instance.nzFilter = [ { name: 'f1', - fn : () => { + fn: () => { return new Observable((observer: Observer) => { observer.error('filter error'); }); @@ -489,24 +494,24 @@ describe('upload', () => { beforeEach(() => { instance.nzFileList = [ { - uid : 1, - name : 'xxx.png', - status : 'done', + uid: 1, + name: 'xxx.png', + status: 'done', response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/xxx.png' + url: 'http://www.baidu.com/xxx.png' }, { - uid : 2, - name : 'yyy.png', + uid: 2, + name: 'yyy.png', status: 'done', - url : 'http://www.baidu.com/yyy.png' + url: 'http://www.baidu.com/yyy.png' }, { - uid : 3, - name : 'zzz.png', - status : 'error', + uid: 3, + name: 'zzz.png', + status: 'error', response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/zzz.png' + url: 'http://www.baidu.com/zzz.png' } ] as any[]; fixture.detectChanges(); @@ -559,14 +564,14 @@ describe('upload', () => { fixture.detectChanges(); pageObject.postSmall(); fixture.detectChanges(); - expect(instance.comp.nzFileList[ 0 ].thumbUrl).toBeUndefined(); + expect(instance.comp.nzFileList[0].thumbUrl).toBeUndefined(); }); it('with picture', () => { instance.nzListType = 'picture'; fixture.detectChanges(); pageObject.postSmall(); fixture.detectChanges(); - expect(instance.comp.nzFileList[ 0 ].thumbUrl).not.toBeUndefined(); + expect(instance.comp.nzFileList[0].thumbUrl).not.toBeUndefined(); }); }); }); @@ -606,7 +611,9 @@ describe('upload', () => { private files: any; constructor() { - spyOn(this.btnComp, 'onClick').and.callFake(() => this.btnComp.onChange({ target: { files: this.files } } as any)); + spyOn(this.btnComp, 'onClick').and.callFake(() => + this.btnComp.onChange({ target: { files: this.files } } as any) + ); } get btnEl(): DebugElement { @@ -622,7 +629,7 @@ describe('upload', () => { } postFile(files: any): this { - this.files = Array.isArray(files) ? files : [ files ]; + this.files = Array.isArray(files) ? files : [files]; this.btnEl.nativeElement.click(); return this; } @@ -655,8 +662,16 @@ describe('upload', () => { let instance: TestUploadListComponent; beforeEach(() => { TestBed.configureTestingModule({ - imports : [ CommonModule, FormsModule, NzToolTipModule, NzProgressModule, NzI18nModule, NoopAnimationsModule, NzIconTestModule ], - declarations: [ NzUploadListComponent, TestUploadListComponent ] + imports: [ + CommonModule, + FormsModule, + NzToolTipModule, + NzProgressModule, + NzI18nModule, + NoopAnimationsModule, + NzIconTestModule + ], + declarations: [NzUploadListComponent, TestUploadListComponent] }); fixture = TestBed.createComponent(TestUploadListComponent); dl = fixture.debugElement; @@ -665,7 +680,7 @@ describe('upload', () => { }); describe('[listType]', () => { - for (const type of [ 'text', 'picture', 'picture-card' ]) { + for (const type of ['text', 'picture', 'picture-card']) { it(`with [${type}]`, () => { instance.listType = type as UploadListType; fixture.detectChanges(); @@ -683,14 +698,14 @@ describe('upload', () => { expect(instance._onPreview).toBe(false); const actions = dl.queryAll(By.css('.ant-upload-list-item-actions')); expect(actions.length).toBe(instance.items.length); - actions[ 0 ].query(By.css('a')).nativeElement.click(); + actions[0].query(By.css('a')).nativeElement.click(); fixture.detectChanges(); expect(instance._onPreview).toBe(true); }); it('should be hide preview', () => { instance.icons = { showPreviewIcon: false, - showRemoveIcon : true + showRemoveIcon: true }; fixture.detectChanges(); const actions = dl.queryAll(By.css('.ant-upload-list-item-actions a')); @@ -701,14 +716,14 @@ describe('upload', () => { expect(instance._onRemove).toBe(false); const actions = dl.queryAll(By.css('.ant-upload-list-item-actions')); expect(actions.length).toBe(instance.items.length); - actions[ 0 ].query(By.css('.anticon-delete')).nativeElement.click(); + actions[0].query(By.css('.anticon-delete')).nativeElement.click(); fixture.detectChanges(); expect(instance._onRemove).toBe(true); }); it('should be hide remove', () => { instance.icons = { showPreviewIcon: true, - showRemoveIcon : false + showRemoveIcon: false }; fixture.detectChanges(); const actions = dl.queryAll(By.css('.ant-upload-list-item-actions .anticon-delete')); @@ -717,13 +732,11 @@ describe('upload', () => { }); it('should be hide preview when is invalid image url', fakeAsync(() => { instance.icons = { - showPreviewIcon : true, - showRemoveIcon : true, + showPreviewIcon: true, + showRemoveIcon: true, hidePreviewIconInNonImage: false }; - instance.items = [ - { url: '1.pdf' } - ]; + instance.items = [{ url: '1.pdf' }]; fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -732,13 +745,11 @@ describe('upload', () => { })); it('should be hide preview when is invalid image url', fakeAsync(() => { instance.icons = { - showPreviewIcon : true, - showRemoveIcon : true, + showPreviewIcon: true, + showRemoveIcon: true, hidePreviewIconInNonImage: true }; - instance.items = [ - { url: '1.pdf' } - ]; + instance.items = [{ url: '1.pdf' }]; fixture.detectChanges(); tick(); fixture.detectChanges(); @@ -763,10 +774,10 @@ describe('upload', () => { it('should support linkProps as object', fakeAsync(() => { instance.items = [ { - uid : '-1', - name : 'foo.png', - status : 'done', - url : 'http://www.baidu.com/xxx.png', + uid: '-1', + name: 'foo.png', + status: 'done', + url: 'http://www.baidu.com/xxx.png', linkProps: { download: 'image' } @@ -782,10 +793,10 @@ describe('upload', () => { const linkPropsString = JSON.stringify({ download: 'image' }); instance.items = [ { - uid : '-1', - name : 'foo.png', - status : 'done', - url : 'http://www.baidu.com/xxx.png', + uid: '-1', + name: 'foo.png', + status: 'done', + url: 'http://www.baidu.com/xxx.png', linkProps: linkPropsString } ]; @@ -845,7 +856,7 @@ describe('upload', () => { class MockFR { result = '1'; - onloadend(): void { } + onloadend(): void {} readAsDataURL(): void { this.onloadend(); @@ -855,18 +866,18 @@ describe('upload', () => { it('should be generate thumb when is valid image data', () => { spyOn(window as any, 'FileReader').and.returnValue(new MockFR()); instance.listType = 'picture'; - instance.items = [ { originFileObj: new File([ '' ], '1.png', { type: 'image' }), thgitumbUrl: undefined } ]; + instance.items = [{ originFileObj: new File([''], '1.png', { type: 'image' }), thgitumbUrl: undefined }]; fixture.detectChanges(); - expect(instance.items[ 0 ].thumbUrl).toBe('1'); + expect(instance.items[0].thumbUrl).toBe('1'); }); it('should be ingore thumb when is invalid image data', () => { const mockFR = new MockFR(); mockFR.result = ''; spyOn(window as any, 'FileReader').and.returnValue(mockFR); instance.listType = 'picture'; - instance.items = [ { originFileObj: new File([ '' ], '1.pdf', { type: 'pdf' }), thumbUrl: undefined } ]; + instance.items = [{ originFileObj: new File([''], '1.pdf', { type: 'pdf' }), thumbUrl: undefined }]; fixture.detectChanges(); - expect(instance.items[ 0 ].thumbUrl).toBe(''); + expect(instance.items[0].thumbUrl).toBe(''); }); }); }); @@ -878,8 +889,8 @@ describe('upload', () => { let instance: TestUploadBtnComponent; beforeEach(() => { TestBed.configureTestingModule({ - imports : [ HttpClientTestingModule, NzIconTestModule ], - declarations: [ NzUploadBtnComponent, TestUploadBtnComponent ] + imports: [HttpClientTestingModule, NzIconTestModule], + declarations: [NzUploadBtnComponent, TestUploadBtnComponent] }); fixture = TestBed.createComponent(TestUploadBtnComponent); dl = fixture.debugElement; @@ -922,8 +933,8 @@ describe('upload', () => { spyOn(instance.comp, 'uploadFiles'); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { files: [ FILE ] }, + type: 'dragend', + dataTransfer: { files: [FILE] }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).toHaveBeenCalled(); @@ -940,8 +951,8 @@ describe('upload', () => { spyOn(instance.comp, 'uploadFiles'); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { files: PNGSMALL.target.files }, + type: 'dragend', + dataTransfer: { files: PNGSMALL.target.files }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); @@ -952,8 +963,8 @@ describe('upload', () => { spyOn(instance.comp, 'uploadFiles'); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { files: PNGSMALL.target.files }, + type: 'dragend', + dataTransfer: { files: PNGSMALL.target.files }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); @@ -964,20 +975,20 @@ describe('upload', () => { spyOn(instance.comp, 'uploadFiles'); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { files: PNGSMALL.target.files }, + type: 'dragend', + dataTransfer: { files: PNGSMALL.target.files }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).toHaveBeenCalled(); }); it(`allow type [ 'image/png', 'image/jpg' ]`, () => { - instance.options.accept = [ 'image/png', 'image/jpg' ]; + instance.options.accept = ['image/png', 'image/jpg']; fixture.detectChanges(); spyOn(instance.comp, 'uploadFiles'); expect(instance.comp.uploadFiles).not.toHaveBeenCalled(); instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { files: PNGSMALL.target.files }, + type: 'dragend', + dataTransfer: { files: PNGSMALL.target.files }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).toHaveBeenCalled(); @@ -994,8 +1005,8 @@ describe('upload', () => { const isDirectory = Array.isArray(item.children); const ret = { isDirectory, - isFile : !isDirectory, - file : (handle: any) => { + isFile: !isDirectory, + file: (handle: any) => { handle(new Item(item.name)); }, createReader: () => { @@ -1007,14 +1018,14 @@ describe('upload', () => { return ret; }; const makeDataTransferItem = (item: Item) => ({ webkitGetAsEntry: () => makeFileSystemEntry(item) }); - beforeEach(() => instance.options.directory = true); + beforeEach(() => (instance.options.directory = true)); it('should working', () => { spyOn(instance.comp, 'uploadFiles'); const files = { - name : 'foo', + name: 'foo', children: [ { - name : 'bar', + name: 'bar', children: [ { name: 'is.webp' @@ -1024,19 +1035,19 @@ describe('upload', () => { ] }; instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { - items: [ makeDataTransferItem(files) ] + type: 'dragend', + dataTransfer: { + items: [makeDataTransferItem(files)] }, preventDefault: () => {} } as any); expect(instance.comp.uploadFiles).toHaveBeenCalled(); }); it('should be ingore invalid extension', () => { - instance.options.accept = [ '.webp' ]; + instance.options.accept = ['.webp']; spyOn(instance.comp, 'uploadFiles'); const files = { - name : 'foo', + name: 'foo', children: [ { name: 'is.jpg' @@ -1044,9 +1055,9 @@ describe('upload', () => { ] }; instance.comp.onFileDrop({ - type : 'dragend', - dataTransfer : { - items: [ makeDataTransferItem(files) ] + type: 'dragend', + dataTransfer: { + items: [makeDataTransferItem(files)] }, preventDefault: () => {} } as any); @@ -1090,10 +1101,7 @@ describe('upload', () => { it('should be abort all uploading file', () => { instance.comp.onChange({ target: { - files: [ - ...PNGSMALL.target.files, - ...JPGSMALL.target.files - ] + files: [...PNGSMALL.target.files, ...JPGSMALL.target.files] } } as any); expect(Object.keys(instance.comp.reqs).length).toBe(2); @@ -1117,64 +1125,62 @@ describe('upload', () => { let http: HttpTestingController; beforeEach(() => { injector = TestBed.configureTestingModule({ - imports : [ HttpClientTestingModule ], - declarations: [ NzUploadBtnComponent ] + imports: [HttpClientTestingModule], + declarations: [NzUploadBtnComponent] }); (injector as TestBed).compileComponents(); fixture = TestBed.createComponent(NzUploadBtnComponent); comp = fixture.debugElement.componentInstance; comp.options = { - action : '/test', - accept : 'image/png', - filters : [], - data : { a: 1 }, - headers : { token: 'asdf' }, - name : 'avatar', - multiple : true, + action: '/test', + accept: 'image/png', + filters: [], + data: { a: 1 }, + headers: { token: 'asdf' }, + name: 'avatar', + multiple: true, withCredentials: true, - beforeUpload : () => true, - onStart : () => {}, - onProgress : () => {}, - onSuccess : () => {}, - onError : () => {} + beforeUpload: () => true, + onStart: () => {}, + onProgress: () => {}, + onSuccess: () => {}, + onError: () => {} } as ZipButtonOptions; http = injector.get(HttpTestingController); }); it('should uploading a png file', fakeAsync(() => { - spyOn(comp.options, 'onStart'); - spyOn(comp.options, 'onProgress'); - spyOn(comp.options, 'onSuccess'); - comp.onChange(PNGSMALL as any); - tick(1); - const req = http.expectOne('/test'); - req.event({ type: 1, loaded: 10, total: 100 }); - req.flush('ok'); - expect(comp.options.onProgress).toHaveBeenCalled(); - expect(comp.options.onStart).toHaveBeenCalled(); - expect(comp.options.onSuccess).toHaveBeenCalled(); - }) - ); + spyOn(comp.options, 'onStart'); + spyOn(comp.options, 'onProgress'); + spyOn(comp.options, 'onSuccess'); + comp.onChange(PNGSMALL as any); + tick(1); + const req = http.expectOne('/test'); + req.event({ type: 1, loaded: 10, total: 100 }); + req.flush('ok'); + expect(comp.options.onProgress).toHaveBeenCalled(); + expect(comp.options.onStart).toHaveBeenCalled(); + expect(comp.options.onSuccess).toHaveBeenCalled(); + })); it('should contain the parameters of http request', fakeAsync(() => { - comp.onChange(PNGSMALL as any); - tick(1); - const req = http.expectOne('/test'); - expect(req.request.withCredentials).toBe(true); - expect(req.request.headers.get('token')).toBe('asdf'); - const body = req.request.body as FormData; - expect(body.has('avatar')).toBe(true); - expect(body.has('a')).toBe(true); - req.flush('ok'); - }) - ); + comp.onChange(PNGSMALL as any); + tick(1); + const req = http.expectOne('/test'); + expect(req.request.withCredentials).toBe(true); + expect(req.request.headers.get('token')).toBe('asdf'); + const body = req.request.body as FormData; + expect(body.has('avatar')).toBe(true); + expect(body.has('a')).toBe(true); + req.flush('ok'); + })); it('should filter size', () => { spyOn(comp.options, 'onStart'); comp.options.filters = [ { name: '', - fn : (fileList: UploadFile[]) => fileList.filter(w => w.size / 1024 <= 0) + fn: (fileList: UploadFile[]) => fileList.filter(w => w.size / 1024 <= 0) } ]; comp.onChange(PNGBIG as any); @@ -1190,17 +1196,16 @@ describe('upload', () => { }); it('should error when request error', fakeAsync(() => { - spyOn(comp.options, 'onStart'); - spyOn(comp.options, 'onSuccess'); - spyOn(comp.options, 'onError'); - comp.onChange(PNGSMALL as any); - tick(1); - http.expectOne('/test').error({ status: 403 } as any); - expect(comp.options.onStart).toHaveBeenCalled(); - expect(comp.options.onError).toHaveBeenCalled(); - expect(comp.options.onSuccess).not.toHaveBeenCalled(); - }) - ); + spyOn(comp.options, 'onStart'); + spyOn(comp.options, 'onSuccess'); + spyOn(comp.options, 'onError'); + comp.onChange(PNGSMALL as any); + tick(1); + http.expectOne('/test').error({ status: 403 } as any); + expect(comp.options.onStart).toHaveBeenCalled(); + expect(comp.options.onError).toHaveBeenCalled(); + expect(comp.options.onSuccess).not.toHaveBeenCalled(); + })); it('should custom request', () => { comp.options.customRequest = () => of(true).subscribe(() => {}); @@ -1211,7 +1216,7 @@ describe('upload', () => { it('should be warn "Must return Subscription type in [nzCustomRequest] property"', () => { let warnMsg = ''; - console.warn = jasmine.createSpy().and.callFake((res: string) => warnMsg = res); + console.warn = jasmine.createSpy().and.callFake((res: string) => (warnMsg = res)); comp.options.customRequest = (() => {}) as any; comp.onChange(PNGSMALL as any); expect(warnMsg).toContain(`Must return Subscription type`); @@ -1222,34 +1227,35 @@ describe('upload', () => { @Component({ template: ` - - + + ` }) @@ -1268,7 +1274,7 @@ class TestUploadComponent { this._beforeUpload = true; this._beforeUploadList = fileList; return true; - } + }; nzCustomRequest: any; nzData: any; nzFilter: UploadFilter[] = []; @@ -1284,31 +1290,38 @@ class TestUploadComponent { _onPreview = false; onPreview = (): void => { this._onPreview = true; - } + }; _onRemove = false; onRemove: null | ((file: UploadFile) => boolean | Observable) = (): boolean => { this._onRemove = true; return true; - } + }; _nzChange: UploadChangeParam; - nzChange(value: UploadChangeParam): void { this._nzChange = value; } + nzChange(value: UploadChangeParam): void { + this._nzChange = value; + } _nzFileListChange: any; - nzFileListChange(value: any): void { this._nzChange = value; } + nzFileListChange(value: any): void { + this._nzChange = value; + } directory = false; } @Component({ - template : ` - `, + template: ` + + `, encapsulation: ViewEncapsulation.None }) class TestUploadListComponent { @@ -1316,53 +1329,54 @@ class TestUploadListComponent { listType: UploadListType = 'picture-card'; items: any[] = [ { - uid : 1, - name : 'xxx.png', - status : 'done', + uid: 1, + name: 'xxx.png', + status: 'done', response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/xxx.png' + url: 'http://www.baidu.com/xxx.png' }, { - uid : 2, - name : 'yyy.png', + uid: 2, + name: 'yyy.png', status: 'done', - url : 'http://www.baidu.com/yyy.png' + url: 'http://www.baidu.com/yyy.png' }, { - uid : 3, - name : 'zzz.png', - status : 'error', + uid: 3, + name: 'zzz.png', + status: 'error', response: 'Server Error 500', // custom error message to show - url : 'http://www.baidu.com/zzz.png' + url: 'http://www.baidu.com/zzz.png' } ]; icons: ShowUploadListInterface = { showPreviewIcon: true, - showRemoveIcon : true + showRemoveIcon: true }; _onPreview = false; onPreview: VoidFunction | null = (): void => { this._onPreview = true; - } + }; _onRemove = false; onRemove: any = (): void => { this._onRemove = true; - } + }; } @Component({ template: ` -
    UPLAOD
    ` +
    UPLAOD
    + ` }) class TestUploadBtnComponent { @ViewChild('btn') comp: NzUploadBtnComponent; - classes: string[] = [ 'test' ]; + classes: string[] = ['test']; options: ZipButtonOptions = { - disabled : false, + disabled: false, openFileDialogOnClick: true, - filters : [], - customRequest : undefined, - onStart : () => {}, - onError : () => {} + filters: [], + customRequest: undefined, + onStart: () => {}, + onError: () => {} }; } diff --git a/package.json b/package.json index d41d9b1ac13..374495af772 100644 --- a/package.json +++ b/package.json @@ -7,31 +7,32 @@ "node": ">=10.9.0 <11.0.0" }, "scripts": { - "start": "ng serve --port 0", - "build-site": "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod", "build-iframe": "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --project=ng-zorro-antd-iframe --prod --base-href ./", - "test": "ng test --watch=false --code-coverage", - "lint": "tslint -c tslint.json 'components/*/*.ts'", - "release": "node ./scripts/publish/publish.js", + "build-site": "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --pkg components/package.json && node ./scripts/site/replace-scope-prefix.js", "doc": "npm run site:init && node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod", + "format:check": "prettier --config ./.prettierrc --list-different \"component/**/*{.ts}\"", + "generate": "ng build ng-zorro-antd-lib", "helper": "bash ./scripts/release-helper.sh", + "integration-cli": "npm run generate && cd integration/angular-cli && npm run integration", + "integration-rollup": "npm run generate && cd integration/rollup && npm run integration", + "integration-webpack": "npm run generate && cd integration/webpack && npm run integration", + "integration": "npm run generate && bash ./integration-test.sh", + "lint": "tslint -c tslint.json 'components/*/*.ts'", "migration-styles": "node ./scripts/build/migration-styles.js", "ng": "ng", - "site": "node ./scripts/site/generate-site", - "site:start": "node ./scripts/site/generate-site init && node ./scripts/site/generateColorLess && ng serve --port 0 --open", - "site:init": "node ./scripts/site/generate-site init && node ./scripts/site/generateColorLess", - "schematic:demo": "node ./scripts/schematics/demo2schematics", - "schematic:tsc": "tsc -p schematics/tsconfig.json", + "postgenerate": "node ./scripts/build/generate-less.js && cp README.md publish/README.md && npm run migration-styles && npm run schematic:generate", + "pre-release": "npm run site:init && bash ./scripts/build/replace-publish.sh && npm run generate && npm run build-site && npm run build-iframe && npm run helper", + "release": "node ./scripts/publish/publish.js", "schematic:build": "node ./scripts/schematics/set-theme.js && node ./scripts/schematics/set-version.js && npm run schematic:tsc && node ./scripts/schematics/copy-resources", + "schematic:demo": "node ./scripts/schematics/demo2schematics", "schematic:generate": "npm run schematic:demo && npm run schematic:build && rm -rf schematics/demo", - "integration": "npm run generate && bash ./integration-test.sh", - "integration-cli": "npm run generate && cd integration/angular-cli && npm run integration", - "integration-webpack": "npm run generate && cd integration/webpack && npm run integration", - "integration-rollup": "npm run generate && cd integration/rollup && npm run integration", - "postgenerate": "node ./scripts/build/generate-less.js && cp README.md publish/README.md && npm run migration-styles && npm run schematic:generate", - "generate": "ng build ng-zorro-antd-lib", - "pre-release": "npm run site:init && bash ./scripts/build/replace-publish.sh && npm run generate && npm run build-site && npm run build-iframe && npm run helper" + "schematic:tsc": "tsc -p schematics/tsconfig.json", + "site:init": "node ./scripts/site/generate-site init && node ./scripts/site/generateColorLess", + "site:start": "node ./scripts/site/generate-site init && node ./scripts/site/generateColorLess && ng serve --port 0 --open", + "site": "node ./scripts/site/generate-site", + "start": "ng serve --port 0", + "test": "ng test --watch=false --code-coverage" }, "dependencies": { "@angular/cdk": "^7.3.0", @@ -47,14 +48,14 @@ "@angular/animations": "~7.2.0", "@angular/cli": "~7.3.1", "@angular/common": "~7.2.0", - "@angular/compiler": "~7.2.0", "@angular/compiler-cli": "~7.2.0", + "@angular/compiler": "~7.2.0", "@angular/core": "~7.2.0", "@angular/forms": "~7.2.0", "@angular/http": "~7.2.0", "@angular/language-service": "~7.2.0", - "@angular/platform-browser": "~7.2.0", "@angular/platform-browser-dynamic": "~7.2.0", + "@angular/platform-browser": "~7.2.0", "@angular/router": "~7.2.0", "@angular/service-worker": "~7.2.0", "@schematics/angular": "~7.2.0", @@ -75,18 +76,20 @@ "hammerjs": "^2.0.8", "husky": "^1.0.1", "jasmine-core": "~2.99.1", - "karma": "~3.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", - "karma-jasmine": "~1.1.2", "karma-jasmine-html-reporter": "^0.2.2", + "karma-jasmine": "~1.1.2", "karma-spec-reporter": "0.0.32", - "less": "^3.9.0", + "karma": "~3.0.0", "less-plugin-clean-css": "^1.5.1", + "less": "^3.9.0", "marked": "^0.5.1", "ng-packagr": "^4.2.0", "ngx-color": "^2.0.5", "node-prismjs": "^0.1.1", + "prettier": "^1.16.4", + "pretty-quick": "^1.10.0", "prismjs": "^1.10.0", "protractor": "~5.4.0", "readline-sync": "^1.4.9", @@ -103,7 +106,8 @@ }, "husky": { "hooks": { - "commit-msg": "node ./scripts/git/commit-msg.js -E HUSKY_GIT_PARAMS" + "commit-msg": "node ./scripts/git/commit-msg.js -E HUSKY_GIT_PARAMS", + "pre-commit": "pretty-quick --staged" } } } diff --git a/schematics/ng-add/index.ts b/schematics/ng-add/index.ts index b09725084b1..38220ba8b8f 100644 --- a/schematics/ng-add/index.ts +++ b/schematics/ng-add/index.ts @@ -4,9 +4,8 @@ import { addPackageToPackageJson } from '../utils/package-config'; import { hammerjsVersion, zorroVersion } from '../utils/version-names'; import { Schema } from './schema'; -export default function (options: Schema): Rule { +export default function(options: Schema): Rule { return (host: Tree, context: SchematicContext) => { - if (!options.skipPackageJson) { addPackageToPackageJson(host, 'ng-zorro-antd', zorroVersion); if (options.gestures) { @@ -16,7 +15,7 @@ export default function (options: Schema): Rule { const installTaskId = context.addTask(new NodePackageInstallTask()); - context.addTask(new RunSchematicTask('ng-add-setup-project', options), [ installTaskId ]); + context.addTask(new RunSchematicTask('ng-add-setup-project', options), [installTaskId]); if (options.bootPage) { context.addTask(new RunSchematicTask('boot-page', options)); diff --git a/schematics/ng-add/schema.ts b/schematics/ng-add/schema.ts index 8d26d343aad..60866a76b5d 100644 --- a/schematics/ng-add/schema.ts +++ b/schematics/ng-add/schema.ts @@ -1,9 +1,39 @@ - -export type Locale = 'ar_EG' | 'bg_BG' | 'ca_ES' | 'cs_CZ' | 'da_DK' | 'de_DE' | 'el_GR' - | 'en_GB' | 'en_US' | 'es_ES' | 'et_EE' | 'fa_IR' | 'fi_FI' | 'fr_BE' | 'fr_FR' - | 'is_IS' | 'it_IT' | 'ja_JP' | 'ko_KR' | 'nb_NO' | 'nl_BE' | 'nl_NL' | 'pl_PL' - | 'pt_BR' | 'pt_PT' | 'sk_SK' | 'sr_RS' | 'sv_SE' | 'th_TH' | 'tr_TR' | 'ru_RU' - | 'uk_UA' | 'vi_VN' | 'zh_CN' | 'zh_TW'; +export type Locale = + | 'ar_EG' + | 'bg_BG' + | 'ca_ES' + | 'cs_CZ' + | 'da_DK' + | 'de_DE' + | 'el_GR' + | 'en_GB' + | 'en_US' + | 'es_ES' + | 'et_EE' + | 'fa_IR' + | 'fi_FI' + | 'fr_BE' + | 'fr_FR' + | 'is_IS' + | 'it_IT' + | 'ja_JP' + | 'ko_KR' + | 'nb_NO' + | 'nl_BE' + | 'nl_NL' + | 'pl_PL' + | 'pt_BR' + | 'pt_PT' + | 'sk_SK' + | 'sr_RS' + | 'sv_SE' + | 'th_TH' + | 'tr_TR' + | 'ru_RU' + | 'uk_UA' + | 'vi_VN' + | 'zh_CN' + | 'zh_TW'; export interface Schema { bootPage?: boolean; diff --git a/schematics/ng-update/index.ts b/schematics/ng-update/index.ts index 509d68a015d..3c117904dcd 100644 --- a/schematics/ng-update/index.ts +++ b/schematics/ng-update/index.ts @@ -8,7 +8,7 @@ const ruleDirectories = globSync('upgrade-rules/**/', { cwd: __dirname, absolute /** TSLint upgrade configuration that will be passed to the CDK ng-update rule. */ const tslintUpgradeConfig: UpgradeTSLintConfig = { - upgradeData : materialUpgradeData, + upgradeData: materialUpgradeData, extraRuleDirectories: ruleDirectories }; @@ -23,7 +23,11 @@ export function postUpdate(): Rule { console.log(); console.log(chalk.green(' ✓ NG-ZORRO update complete')); console.log(); - console.log(chalk.yellow(' ⚠ Please check the output above for any issues that were detected ' + - 'but could not be automatically fixed.')); + console.log( + chalk.yellow( + ' ⚠ Please check the output above for any issues that were detected ' + + 'but could not be automatically fixed.' + ) + ); }; } diff --git a/schematics/utils/package-config.ts b/schematics/utils/package-config.ts index 6f690c32ab2..f5b54faa2af 100644 --- a/schematics/utils/package-config.ts +++ b/schematics/utils/package-config.ts @@ -5,12 +5,13 @@ import { Tree } from '@angular-devkit/schematics'; * @returns A new object instance with sorted keys */ function sortObjectByKeys(obj: object): object { - return Object.keys(obj).sort().reduce((result, key) => (result[ key ] = obj[ key ]) && result, {}); + return Object.keys(obj) + .sort() + .reduce((result, key) => (result[key] = obj[key]) && result, {}); } /** Adds a package to the package.json in the given host tree. */ export function addPackageToPackageJson(host: Tree, pkg: string, version: string): Tree { - if (host.exists('package.json')) { const sourceText = host.read('package.json').toString('utf-8'); const json = JSON.parse(sourceText); @@ -19,8 +20,8 @@ export function addPackageToPackageJson(host: Tree, pkg: string, version: string json.dependencies = {}; } - if (!json.dependencies[ pkg ]) { - json.dependencies[ pkg ] = version; + if (!json.dependencies[pkg]) { + json.dependencies[pkg] = version; json.dependencies = sortObjectByKeys(json.dependencies); } @@ -38,8 +39,8 @@ export function getPackageVersionFromPackageJson(tree: Tree, name: string): stri const packageJson = JSON.parse(tree.read('package.json').toString('utf8')); - if (packageJson.dependencies && packageJson.dependencies[ name ]) { - return packageJson.dependencies[ name ]; + if (packageJson.dependencies && packageJson.dependencies[name]) { + return packageJson.dependencies[name]; } return null; diff --git a/scripts/schematics/template/index.ts b/scripts/schematics/template/index.ts index fd0b5c8c4f3..9b8502cc25b 100644 --- a/scripts/schematics/template/index.ts +++ b/scripts/schematics/template/index.ts @@ -2,11 +2,14 @@ import { chain, Rule } from '@angular-devkit/schematics'; import { buildComponent } from '@angular/cdk/schematics'; import { Schema } from './schema'; -export default function (options: Schema): Rule { +export default function(options: Schema): Rule { return chain([ - buildComponent({ ...options }, { - template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html', - stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__styleext__' - }) + buildComponent( + { ...options }, + { + template: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.html', + stylesheet: './__path__/__name@dasherize@if-flat__/__name@dasherize__.component.__styleext__' + } + ) ]); } diff --git a/scripts/site/_site/doc/app/_demo/demo.component.ts b/scripts/site/_site/doc/app/_demo/demo.component.ts index 0d0a448ea8c..9a5b7a2279c 100644 --- a/scripts/site/_site/doc/app/_demo/demo.component.ts +++ b/scripts/site/_site/doc/app/_demo/demo.component.ts @@ -7,6 +7,4 @@ import { Component } from '@angular/core'; selector: 'nz-demo-COMPONENTNAME-basic', template: `` }) -export class DEMOComponent { - -} +export class DEMOComponent {} diff --git a/scripts/site/_site/doc/app/app.component.ts b/scripts/site/_site/doc/app/app.component.ts index 158d8e4b3c7..0669737affb 100644 --- a/scripts/site/_site/doc/app/app.component.ts +++ b/scripts/site/_site/doc/app/app.component.ts @@ -1,12 +1,4 @@ -import { - AfterViewInit, - Component, - ElementRef, - HostListener, - NgZone, - OnInit, - ViewChild -} from '@angular/core'; +import { AfterViewInit, Component, ElementRef, HostListener, NgZone, OnInit, ViewChild } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { NavigationEnd, Router } from '@angular/router'; import { en_US, NzI18nService, NzMessageService, zh_CN } from 'ng-zorro-antd'; @@ -26,7 +18,7 @@ interface DocPageMeta { } @Component({ - selector : 'app-root', + selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit, AfterViewInit { @@ -46,12 +38,7 @@ export class AppComponent implements OnInit, AfterViewInit { } language = 'zh'; - oldVersionList = [ - '0.5.x', - '0.6.x', - '0.7.x', - '1.8.x' - ]; + oldVersionList = ['0.5.x', '0.6.x', '0.7.x', '1.8.x']; currentVersion = '7.0.3'; @ViewChild('searchInput') searchInput: ElementRef; @@ -64,7 +51,6 @@ export class AppComponent implements OnInit, AfterViewInit { toggleMenu(): void { if (this.showDrawer) { - } } @@ -73,8 +59,8 @@ export class AppComponent implements OnInit, AfterViewInit { private title: Title, private nzI18nService: NzI18nService, private msg: NzMessageService, - private ngZone: NgZone) { - } + private ngZone: NgZone + ) {} navigateToPage(url: string) { if (url) { @@ -93,7 +79,7 @@ export class AppComponent implements OnInit, AfterViewInit { ngOnInit(): void { this.routerList.components.forEach(group => { - this.componentList = this.componentList.concat([ ...group.children ]); + this.componentList = this.componentList.concat([...group.children]); }); this.router.events.subscribe(event => { @@ -118,7 +104,7 @@ export class AppComponent implements OnInit, AfterViewInit { this.nzI18nService.setLocale(this.language === 'en' ? en_US : zh_CN); if (this.docsearch) { - this.docsearch!.algoliaOptions = { hitsPerPage: 5, facetFilters: [ `tags:${this.language}` ] }; + this.docsearch!.algoliaOptions = { hitsPerPage: 5, facetFilters: [`tags:${this.language}`] }; } if (environment.production) { @@ -149,24 +135,26 @@ export class AppComponent implements OnInit, AfterViewInit { initDocsearch() { this.loadScript('https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js').then(() => { this.docsearch = docsearch({ - appId : 'PO5D2PCS2I', - apiKey : 'cda01b4d7172b1582a2911ef08519f62', - indexName : 'dev_ng_zorro', - inputSelector : '#search-box input', - algoliaOptions: { hitsPerPage: 5, facetFilters: [ `tags:${this.language}` ] }, - transformData(hits: any) { // tslint:disable-line:no-any - hits.forEach((hit: any) => { // tslint:disable-line:no-any + appId: 'PO5D2PCS2I', + apiKey: 'cda01b4d7172b1582a2911ef08519f62', + indexName: 'dev_ng_zorro', + inputSelector: '#search-box input', + algoliaOptions: { hitsPerPage: 5, facetFilters: [`tags:${this.language}`] }, + transformData(hits: any) { + // tslint:disable-line:no-any + hits.forEach((hit: any) => { + // tslint:disable-line:no-any hit.url = hit.url.replace('ng.ant.design', location.host); hit.url = hit.url.replace('https:', location.protocol); }); return hits; }, - debug : false + debug: false }); }); } - @HostListener('document:keyup.s', [ '$event' ]) + @HostListener('document:keyup.s', ['$event']) onKeyUp(event: KeyboardEvent) { if (this.useDocsearch && this.searchInput && this.searchInput.nativeElement && event.target === document.body) { this.searchInput.nativeElement.focus(); @@ -181,20 +169,22 @@ export class AppComponent implements OnInit, AfterViewInit { node.rel = 'stylesheet/less'; node.type = 'text/css'; node.href = '/assets/color.less'; - document.getElementsByTagName('head')[ 0 ].appendChild(node); + document.getElementsByTagName('head')[0].appendChild(node); } lessLoaded = false; changeColor(res: any) { const changeColor = () => { - (window as any).less.modifyVars({ - '@primary-color': res.color.hex - }).then(() => { - this.msg.success(`应用成功`); - this.color = res.color.hex; - window.scrollTo(0, 0); - }); + (window as any).less + .modifyVars({ + '@primary-color': res.color.hex + }) + .then(() => { + this.msg.success(`应用成功`); + this.color = res.color.hex; + window.scrollTo(0, 0); + }); }; const lessUrl = 'https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js'; @@ -226,16 +216,18 @@ export class AppComponent implements OnInit, AfterViewInit { // endregion private addWindowWidthListener(): void { this.ngZone.runOutsideAngular(() => { - fromEvent(window, 'resize').pipe( - startWith(true), - debounceTime(50), - map(() => window.innerWidth) - ).subscribe(width => { - const showDrawer = width <= 768; - if (this.showDrawer !== showDrawer) { - this.showDrawer = showDrawer; - } - }); + fromEvent(window, 'resize') + .pipe( + startWith(true), + debounceTime(50), + map(() => window.innerWidth) + ) + .subscribe(width => { + const showDrawer = width <= 768; + if (this.showDrawer !== showDrawer) { + this.showDrawer = showDrawer; + } + }); }); } diff --git a/scripts/site/_site/doc/app/app.module.ts b/scripts/site/_site/doc/app/app.module.ts index a3c53b300d6..c9bd3d64ec8 100644 --- a/scripts/site/_site/doc/app/app.module.ts +++ b/scripts/site/_site/doc/app/app.module.ts @@ -15,13 +15,11 @@ import { AppComponent } from './app.component'; import { routes } from './app.routing.module'; import { ShareModule } from './share/share.module'; -const icons: IconDefinition[] = [ LeftOutline, RightOutline ]; +const icons: IconDefinition[] = [LeftOutline, RightOutline]; @NgModule({ - declarations: [ - AppComponent, DEMOComponent - ], - imports : [ + declarations: [AppComponent, DEMOComponent], + imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, @@ -32,12 +30,11 @@ const icons: IconDefinition[] = [ LeftOutline, RightOutline ]; RouterModule.forRoot(routes, environment.production ? { preloadingStrategy: PreloadAllModules } : {}), ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) ], - providers : [ + providers: [ Title, { provide: NZ_ICONS, useValue: icons }, { provide: NZ_ICON_DEFAULT_TWOTONE_COLOR, useValue: '#1890ff' } ], - bootstrap : [ AppComponent ] + bootstrap: [AppComponent] }) -export class AppModule { -} +export class AppModule {} diff --git a/scripts/site/_site/doc/app/app.routing.module.ts b/scripts/site/_site/doc/app/app.routing.module.ts index 7c89da48e61..7631bc3e125 100644 --- a/scripts/site/_site/doc/app/app.routing.module.ts +++ b/scripts/site/_site/doc/app/app.routing.module.ts @@ -6,7 +6,7 @@ import { DEMOComponent } from './_demo/demo.component'; export const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: '/docs/introduce/en' }, ...DEMO_ROUTES, - { 'path': 'docs', 'loadChildren': './docs/index.module#NzDocsModule' }, + { path: 'docs', loadChildren: './docs/index.module#NzDocsModule' }, { path: 'demo', component: DEMOComponent }, { path: '**', redirectTo: '/docs/introduce/zh', pathMatch: 'full' } ]; diff --git a/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.component.ts b/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.component.ts index 688810a40ef..f7e52961287 100644 --- a/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.component.ts +++ b/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.component.ts @@ -5,14 +5,19 @@ import sdk from '@stackblitz/sdk'; import { environment } from '../../../environments/environment'; @Component({ - selector : 'nz-code-box', + selector: 'nz-code-box', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, - template : ` -
    + template: ` +
    -
    +
    @@ -21,30 +26,61 @@ import { environment } from '../../../environments/environment';
    - - - expand code - expand code + + + expand code + expand code
    -
    +
    - - - + + +
    @@ -52,9 +88,7 @@ import { environment } from '../../../environments/environment';
    `, - styleUrls : [ - './nz-codebox.less' - ] + styleUrls: ['./nz-codebox.less'] }) export class NzCodeBoxComponent { rawCode: string; @@ -76,8 +110,8 @@ export class NzCodeBoxComponent { @Input() set nzIframeSource(value: string) { - this.showIframe = (value !== 'null') && environment.production; - this.simulateIFrame = (value !== 'null') && !environment.production; + this.showIframe = value !== 'null' && environment.production; + this.simulateIFrame = value !== 'null' && !environment.production; this.iframe = this.sanitizer.bypassSecurityTrustResourceUrl(value); } @@ -113,7 +147,6 @@ export class NzCodeBoxComponent { } copy(value: string): Promise { - const promise = new Promise( (resolve): void => { // @ts-ignore @@ -136,15 +169,14 @@ export class NzCodeBoxComponent { } ); - return (promise); - + return promise; } /** bug here https://github.com/stackblitz/core/issues/311 **/ openOnStackBlitz() { sdk.openProject({ files: { - 'angular.json' : `{ + 'angular.json': `{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", @@ -267,8 +299,8 @@ export class NzCodeBoxComponent { }, "defaultProject": "demo" }`, - 'src/index.html' : `<${this.nzSelector}>loading`, - 'src/main.ts' : `import './polyfills'; + 'src/index.html': `<${this.nzSelector}>loading`, + 'src/main.ts': `import './polyfills'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; @@ -284,7 +316,7 @@ platformBrowserDynamic().bootstrapModule(AppModule).then(ref => { // Otherwise, log the boot error }).catch(err => console.error(err));`, - 'src/polyfills.ts' : `/** + 'src/polyfills.ts': `/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * @@ -352,7 +384,7 @@ import 'zone.js/dist/zone'; // Included with Angular CLI. */ // import 'intl'; // Run \`npm install --save intl\`.`, 'src/app/app.component.ts': this.nzRawCode, - 'src/app/app.module.ts' : `import { NgModule } from '@angular/core'; + 'src/app/app.module.ts': `import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @@ -381,34 +413,33 @@ const icons: IconDefinition[] = Object.keys(antDesignIcons).map(key => antDesign }) export class AppModule { } `, - 'src/styles.css' : `/* Add application styles & imports to this file! */;` + 'src/styles.css': `/* Add application styles & imports to this file! */;` }, - title : 'Dynamically Generated Project', - description : 'Created with <3 by the StackBlitz SDK!', - template : 'angular-cli', + title: 'Dynamically Generated Project', + description: 'Created with <3 by the StackBlitz SDK!', + template: 'angular-cli', dependencies: { - 'rxjs' : '^6.3.3', - '@angular/cdk' : '^7.0.0', - '@angular/core' : '^7.0.0', - '@angular/forms' : '^7.0.0', - '@angular/http' : '^7.0.0', - '@angular/language-service' : '^7.0.0', - '@angular/platform-browser' : '^7.0.0', + rxjs: '^6.3.3', + '@angular/cdk': '^7.0.0', + '@angular/core': '^7.0.0', + '@angular/forms': '^7.0.0', + '@angular/http': '^7.0.0', + '@angular/language-service': '^7.0.0', + '@angular/platform-browser': '^7.0.0', '@angular/platform-browser-dynamic': '^7.0.0', - '@angular/common' : '^7.0.0', - '@angular/router' : '^7.0.0', - '@angular/animations' : '^7.0.0', - '@ant-design/icons-angular' : '^2.0.2', - 'date-fns' : '^1.29.0', - 'tslib' : '^1.9.3', - 'typescript' : '~3.1.1', - 'ng-zorro-antd' : '^7.0.3' + '@angular/common': '^7.0.0', + '@angular/router': '^7.0.0', + '@angular/animations': '^7.0.0', + '@ant-design/icons-angular': '^2.0.2', + 'date-fns': '^1.29.0', + tslib: '^1.9.3', + typescript: '~3.1.1', + 'ng-zorro-antd': '^7.0.3' }, - tags : [ 'stackblitz', 'sdk' ] + tags: ['stackblitz', 'sdk'] }); } - constructor(@Inject(DOCUMENT) private dom: any, private sanitizer: DomSanitizer) { - } + constructor(@Inject(DOCUMENT) private dom: any, private sanitizer: DomSanitizer) {} } diff --git a/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.module.ts b/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.module.ts index 03114a1fdd7..fee2b7fc298 100644 --- a/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.module.ts +++ b/scripts/site/_site/doc/app/share/nz-codebox/nz-codebox.module.ts @@ -5,11 +5,8 @@ import { NzHighlightModule } from '../nz-highlight/nz-highlight.module'; import { NgZorroAntdModule } from 'ng-zorro-antd'; @NgModule({ - imports : [ CommonModule, NzHighlightModule, NgZorroAntdModule ], - declarations: [ NzCodeBoxComponent ], - exports : [ NzCodeBoxComponent ] + imports: [CommonModule, NzHighlightModule, NgZorroAntdModule], + declarations: [NzCodeBoxComponent], + exports: [NzCodeBoxComponent] }) - -export class NzCodeBoxModule { -} - +export class NzCodeBoxModule {} diff --git a/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.component.ts b/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.component.ts index dbea18ad206..8361aad7daa 100644 --- a/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.component.ts +++ b/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.component.ts @@ -20,9 +20,7 @@ export class NzHighlightComponent implements OnInit { this._code = decodeURIComponent(value).trim(); } - constructor() { - } + constructor() {} - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.module.ts b/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.module.ts index aa04b53ca7c..e8cdeb0e20e 100644 --- a/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.module.ts +++ b/scripts/site/_site/doc/app/share/nz-highlight/nz-highlight.module.ts @@ -3,10 +3,8 @@ import { NgModule } from '@angular/core'; import { NzHighlightComponent } from './nz-highlight.component'; @NgModule({ - imports : [ CommonModule ], - declarations: [ NzHighlightComponent ], - exports : [ NzHighlightComponent ] + imports: [CommonModule], + declarations: [NzHighlightComponent], + exports: [NzHighlightComponent] }) -export class NzHighlightModule { - -} +export class NzHighlightModule {} diff --git a/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.component.ts b/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.component.ts index 2b3fa982ecd..109337ffbc7 100644 --- a/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.component.ts +++ b/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.component.ts @@ -7,11 +7,13 @@ import { ROUTER_LIST } from '../../router'; changeDetection: ChangeDetectionStrategy.OnPush, template: `
    - - {{ list[index - 1]?.label }} + + {{ list[index - 1]?.label + }} - - {{ list[index + 1]?.label }} + + {{ list[index + 1]?.label + }}
    ` @@ -21,19 +23,23 @@ export class NzNavBottomComponent implements OnInit { index = 0; language = 'en'; - constructor(private router: Router) { - - } + constructor(private router: Router) {} ngOnInit(): void { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { const url = window.location.pathname.slice(1); - this.language = this.router.url.split('/')[ this.router.url.split('/').length - 1 ].split('#')[ 0 ]; - const componentsList = ROUTER_LIST.components.reduce((pre, cur) => { - return pre.concat(cur.children); - }, [] as any[]); - this.list = [ ...ROUTER_LIST.intro.filter(item => item.language === this.language), ...componentsList.filter(item => item.language === this.language) ]; + this.language = this.router.url.split('/')[this.router.url.split('/').length - 1].split('#')[0]; + const componentsList = ROUTER_LIST.components.reduce( + (pre, cur) => { + return pre.concat(cur.children); + }, + [] as any[] + ); + this.list = [ + ...ROUTER_LIST.intro.filter(item => item.language === this.language), + ...componentsList.filter(item => item.language === this.language) + ]; this.index = this.list.findIndex(item => item.path === url); } }); diff --git a/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.module.ts b/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.module.ts index d19762b78dc..3afb152bd61 100644 --- a/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.module.ts +++ b/scripts/site/_site/doc/app/share/nz-nav-bottom/nz-nav-bottom.module.ts @@ -5,10 +5,8 @@ import { NgZorroAntdModule } from 'ng-zorro-antd'; import { NzNavBottomComponent } from './nz-nav-bottom.component'; @NgModule({ - imports : [ CommonModule, RouterModule, NgZorroAntdModule ], - declarations: [ NzNavBottomComponent ], - exports : [ NzNavBottomComponent ] + imports: [CommonModule, RouterModule, NgZorroAntdModule], + declarations: [NzNavBottomComponent], + exports: [NzNavBottomComponent] }) -export class NzNavBottomModule { - -} +export class NzNavBottomModule {} diff --git a/scripts/site/_site/doc/app/share/share.module.ts b/scripts/site/_site/doc/app/share/share.module.ts index 09d071d0d0c..27b7bd8272e 100644 --- a/scripts/site/_site/doc/app/share/share.module.ts +++ b/scripts/site/_site/doc/app/share/share.module.ts @@ -4,9 +4,7 @@ import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; -import { - NgZorroAntdModule -} from 'ng-zorro-antd'; +import { NgZorroAntdModule } from 'ng-zorro-antd'; import { ColorSketchModule } from 'ngx-color/sketch'; import { NzCodeBoxModule } from './nz-codebox/nz-codebox.module'; import { NzHighlightModule } from './nz-highlight/nz-highlight.module'; @@ -41,5 +39,4 @@ import { NzNavBottomModule } from './nz-nav-bottom/nz-nav-bottom.module'; DragDropModule ] }) -export class ShareModule { -} +export class ShareModule {} diff --git a/scripts/site/_site/doc/main.ts b/scripts/site/_site/doc/main.ts index 8fb728d454d..7a935d577c1 100644 --- a/scripts/site/_site/doc/main.ts +++ b/scripts/site/_site/doc/main.ts @@ -12,5 +12,6 @@ if (environment.production) { enableProdMode(); } -platformBrowserDynamic().bootstrapModule(AppModule) -.catch(err => console.log(err)); +platformBrowserDynamic() + .bootstrapModule(AppModule) + .catch(err => console.log(err)); diff --git a/scripts/site/_site/doc/polyfills.ts b/scripts/site/_site/doc/polyfills.ts index b4eac4aae61..c38dfdafbf0 100644 --- a/scripts/site/_site/doc/polyfills.ts +++ b/scripts/site/_site/doc/polyfills.ts @@ -19,7 +19,7 @@ */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ -import 'classlist.js'; // Run `npm install --save classlist.js`. +import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` @@ -55,8 +55,7 @@ import 'classlist.js'; // Run `npm install --save classlist.js`. /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - +import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS diff --git a/scripts/site/_site/iframe/app/app.component.ts b/scripts/site/_site/iframe/app/app.component.ts index 5793924ddc3..f45969e5cde 100644 --- a/scripts/site/_site/iframe/app/app.component.ts +++ b/scripts/site/_site/iframe/app/app.component.ts @@ -1,8 +1,7 @@ import { Component } from '@angular/core'; @Component({ - selector : 'app-root', + selector: 'app-root', templateUrl: './app.component.html' }) -export class AppComponent { -} +export class AppComponent {} diff --git a/scripts/site/_site/iframe/main.ts b/scripts/site/_site/iframe/main.ts index 8fb728d454d..7a935d577c1 100644 --- a/scripts/site/_site/iframe/main.ts +++ b/scripts/site/_site/iframe/main.ts @@ -12,5 +12,6 @@ if (environment.production) { enableProdMode(); } -platformBrowserDynamic().bootstrapModule(AppModule) -.catch(err => console.log(err)); +platformBrowserDynamic() + .bootstrapModule(AppModule) + .catch(err => console.log(err)); diff --git a/scripts/site/_site/iframe/polyfills.ts b/scripts/site/_site/iframe/polyfills.ts index b4eac4aae61..c38dfdafbf0 100644 --- a/scripts/site/_site/iframe/polyfills.ts +++ b/scripts/site/_site/iframe/polyfills.ts @@ -19,7 +19,7 @@ */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ -import 'classlist.js'; // Run `npm install --save classlist.js`. +import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` @@ -55,8 +55,7 @@ import 'classlist.js'; // Run `npm install --save classlist.js`. /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ -import 'zone.js/dist/zone'; // Included with Angular CLI. - +import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS diff --git a/tslint.json b/tslint.json index 318dca8821a..45da1b4a015 100644 --- a/tslint.json +++ b/tslint.json @@ -1,7 +1,5 @@ { - "rulesDirectory": [ - "node_modules/codelyzer" - ], + "rulesDirectory": ["node_modules/codelyzer"], "rules": { "banana-in-box": true, "templates-no-negated-async": true, @@ -26,72 +24,22 @@ "component-class-suffix": true, "directive-class-suffix": true, "pipe-impure": true, - "angular-whitespace": [ - false, - "check-interpolation", - "check-semicolon" - ], - "directive-selector": [ - true, - "attribute", - [ - "nz" - ], - [ - "camelCase", - "kebab-case" - ] - ], - "component-selector": [ - true, - [ - "element", - "attribute" - ], - [ - "nz", - "test" - ], - "kebab-case" - ], + "angular-whitespace": [false, "check-interpolation"], + "directive-selector": [true, "attribute", ["nz"], ["camelCase", "kebab-case"]], + "component-selector": [true, ["element", "attribute"], ["nz", "test"], "kebab-case"], "callable-types": true, "class-name": true, - "comment-format": [ - true, - "check-space" - ], - "align": [ - true, - "parameters", - "statements" - ], - "array-type": [ - true, - "array-simple" - ], + "comment-format": [true, "check-space"], + "align": [true, "parameters", "statements"], + "array-type": [true, "array-simple"], "arrow-return-shorthand": true, "ban-types": [ true, - [ - "Object", - "Use {} instead." - ], - [ - "String", - "Use string instead." - ], - [ - "Number", - "Use number instead." - ], - [ - "Boolean", - "Use boolean instead." - ], - [ - "Function", - "Use specific callable interface instead." - ] + ["Object", "Use {} instead."], + ["String", "Use string instead."], + ["Number", "Use number instead."], + ["Boolean", "Use boolean instead."], + ["Function", "Use specific callable interface instead."] ], "binary-expression-operand-order": true, "curly": true, @@ -101,14 +49,8 @@ "severity": "warn" }, "import-spacing": true, - "indent": [ - true, - "spaces" - ], - "interface-name": [ - true, - "never-prefix" - ], + "indent": [true, "spaces"], + "interface-name": [true, "never-prefix"], "interface-over-type-literal": true, "label-position": true, "new-parens": true, @@ -117,17 +59,8 @@ "no-any": true, "no-arg": true, "no-bitwise": false, - "no-consecutive-blank-lines": [ - true - ], - "no-console": [ - true, - "debug", - "info", - "time", - "timeEnd", - "trace" - ], + "no-consecutive-blank-lines": [true], + "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], "no-duplicate-variable": true, "no-conditional-assignment": true, "no-construct": true, @@ -140,20 +73,13 @@ "no-floating-promises": false, "no-for-in-array": true, "no-import-side-effect": true, - "no-inferrable-types": [ - true, - "ignore-params", - "ignore-properties" - ], + "no-inferrable-types": [true, "ignore-params", "ignore-properties"], "no-invalid-template-strings": true, "no-invalid-this": true, "no-irregular-whitespace": true, "no-magic-numbers": false, "no-misused-new": true, - "no-namespace": [ - true, - "allow-declarations" - ], + "no-namespace": [true, "allow-declarations"], "no-non-null-assertion": false, "no-shadowed-variable": true, "no-sparse-arrays": true, @@ -168,22 +94,8 @@ "no-use-before-declare": true, "no-var-keyword": true, "number-literal-format": true, - "object-literal-key-quotes": [ - true, - "consistent" - ], - "object-literal-shorthand": true, - "one-line": [ - true, - "check-open-brace", - "check-catch", - "check-else", - "check-whitespace" - ], - "one-variable-per-declaration": [ - true, - "ignore-for-loop" - ], + "one-line": [true, "check-open-brace", "check-catch", "check-else", "check-whitespace"], + "one-variable-per-declaration": [true, "ignore-for-loop"], "ordered-imports": [ true, { @@ -196,19 +108,8 @@ "prefer-for-of": true, "prefer-method-signature": true, "prefer-object-spread": true, - "prefer-template": [ - true, - "allow-single-concat" - ], - "quotemark": [ - true, - "single" - ], + "prefer-template": [true, "allow-single-concat"], "radix": true, - "semicolon": [ - true, - "always" - ], "trailing-comma": [ true, { @@ -216,16 +117,8 @@ "singleline": "never" } ], - "triple-equals": [ - true, - "allow-null-check" - ], - "typedef": [ - true, - "call-signature", - "parameter", - "property-declaration" - ], + "triple-equals": [true, "allow-null-check"], + "typedef": [true, "call-signature", "parameter", "property-declaration"], "typedef-whitespace": [ true, { @@ -238,11 +131,7 @@ ], "unified-signatures": true, "use-isnan": true, - "variable-name": [ - true, - "ban-keywords", - "allow-leading-underscore" - ], + "variable-name": [true, "ban-keywords", "allow-leading-underscore"], "whitespace": [ true, "check-branch",