@angular/core#OnChanges TypeScript Examples

The following examples show how to use @angular/core#OnChanges. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: star.component.ts    From Angular-ActionStreams with MIT License 6 votes vote down vote up
@Component({
  selector: 'pm-star',
  templateUrl: './star.component.html',
  styleUrls: ['./star.component.css']
})
export class StarComponent implements OnChanges {
  @Input() rating = 0;
  starWidth = 0;
  @Output() ratingClicked: EventEmitter<string> =
    new EventEmitter<string>();

  ngOnChanges(): void {
    this.starWidth = this.rating * 75 / 5;
  }

  onClick(): void {
    this.ratingClicked.emit(`The rating ${this.rating} was clicked!`);
  }
}
Example #2
Source File: focus.directive.ts    From canopy with Apache License 2.0 6 votes vote down vote up
@Directive({
  selector: '[lgFocus]',
})
export class LgFocusDirective implements OnChanges {
  @Input() lgFocus: boolean;

  constructor(private el: ElementRef) {}

  ngOnChanges({ lgFocus }: SimpleChanges) {
    if (lgFocus.currentValue) {
      const el = this.el.nativeElement as HTMLElement;

      el.focus();
    }
  }
}
Example #3
Source File: childTest.c.ts    From ngx-dynamic-hooks with MIT License 6 votes vote down vote up
@Component({
  selector: 'dynhooks-childtest',
  templateUrl: './childTest.c.html',
  styleUrls: ['./childTest.c.scss'],
})
export class ChildTestComponent implements DoCheck, OnInit, OnChanges, AfterViewInit, OnDestroy {

  constructor(private cd: ChangeDetectorRef, @Optional() @Inject(BLUBBSERVICETOKEN) private blubbService: any) {
    console.log('CHILD_TEST', this.blubbService);
  }


  ngOnInit () {
    // console.log('textbox init');
  }

  ngOnChanges(changes: any) {
    // console.log('textbox changes');
  }

  ngDoCheck() {
    // console.log('textbox doCheck');
  }

  ngAfterViewInit() {
    // console.log('textbox afterviewinit');
  }

  ngOnDestroy() {
    // console.log('textbox destroy');
  }

}
Example #4
Source File: vc-logs.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-vc-logs',
  templateUrl: './vc-logs.component.html',
  styleUrls: ['./vc-logs.component.scss'],
})
export class VcLogsComponent implements OnInit, OnChanges {
  @Input() vName;
  logs: string[] = [];
  constructor() {}

  ngOnInit(): void {}

  ngOnChanges(changes: SimpleChanges) {
    const currValue = changes.vName.currentValue;
    if (changes.vName.isFirstChange()) {
      this.logs.push(`initial version is ${currValue.trim()}`);
    } else {
      this.logs.push(`version changed to ${currValue.trim()}`);
    }
  }
}
Example #5
Source File: intention-accordion-item.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
@Component({
  selector: 'devtools-intention-accordion-item',
  templateUrl: './intention-accordion-item.component.html',
  styleUrls: ['./intention-accordion-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class IntentionAccordionItemComponent implements OnChanges {

  public nullProvider$: Observable<boolean>;

  @Input()
  public intention: Intention;

  constructor(private _manifestService: DevToolsManifestService) {
  }

  public ngOnChanges(changes: SimpleChanges): void {
    this.nullProvider$ = this._manifestService.capabilityProviders$(this.intention)
      .pipe(map(apps => apps.length === 0));
  }
}
Example #6
Source File: ai-toggle.component.ts    From colo-calc with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Component({
  selector: 'app-ai-toggle',
  templateUrl: './ai-toggle.component.html',
  styleUrls: ['./ai-toggle.component.scss']
})
export class AiToggleComponent implements OnInit, OnChanges {
  @Input() public tile: Tile = null;
  public isChecked: boolean;

  constructor() { }

  ngOnInit() {
  }

  public ngOnChanges() {
    //this.isChecked = !validTileId(this.tile) ? true: this.tile.aiType === CharType.Ranged;
  }

  public onUpdateToggle(e: any) {
    const updatedAiType = e as CharType;
    this.tile.onAiChange({
      ...this.tile,
      //aiType: updatedAiType
    });
  }

}
Example #7
Source File: preview-template.component.ts    From ASW-Form-Builder with MIT License 6 votes vote down vote up
@Component({
    selector: 'asw-preview',
    templateUrl: './preview-template.component.html'
})
export class PreviewTemplateComponent implements OnInit, OnChanges {
    title = 'ASW-Form-Builder-demo';
    jsonData: any[] = [];
    constructor(private aswSettingsService: AswSettingsService) {

    }
    ngOnInit(): void {
        this.jsonData = this.aswSettingsService.previewData;
    }
    ngOnChanges(): void {
        debugger;
        this.aswSettingsService.previewData = this.jsonData;
    }
}
Example #8
Source File: scroll-down.directive.ts    From t3mpl-editor with MIT License 6 votes vote down vote up
@Directive({
	selector: '[appScrollDown]'
})
export class ScrollDownDirective implements OnChanges {

	@Input()
	public follow: any;

	public constructor(
		private readonly el: ElementRef<HTMLElement>) {
	}

	public ngOnChanges() {
		setTimeout(() => {
			this.el.nativeElement.scrollTop = this.el.nativeElement.scrollHeight;
		});
	}
}
Example #9
Source File: chip-label.component.ts    From qbit-matUI with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-chip-label',
  templateUrl: './chip-label.component.html',
  styleUrls: ['./chip-label.component.css']
})
export class ChipLabelComponent implements OnChanges {
  @Input() label: string = '';
  public isDarkTheme: Observable<boolean>;

  constructor(private theme: ThemeService) { }

  ngOnInit(): void {
    this.isDarkTheme = this.theme.getThemeSubscription();
  }

  ngOnChanges(changes: SimpleChanges) {
    if(changes.label)
      this.label = changes.label.currentValue;
  }

}
Example #10
Source File: error.component.ts    From blockcore-explorer with MIT License 6 votes vote down vote up
@Component({
   selector: 'app-error',
   templateUrl: './error.component.html'
})
export class ErrorComponent implements OnChanges {
   @Input() error;
   message: string;
   details: string;
   stack: string;
   detailsVisible = false;

   ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
      if (!this.error) {
         return;
      }

      if (this.error instanceof HttpError) {

         if (this.error.code === 404) {
            this.message = 'Not found (404)';
            this.details = this.error.url;
            this.stack = this.error.stack.toString();
         } else {
            this.message = this.error.message + ' (' + this.error.code + ')';
            this.details = this.error.url;
            this.stack = this.error.stack.toString();
         }
      } else if (this.error instanceof Error) {
         this.message = 'Error occured: ' + this.error.message;
         this.stack = this.error.stack.toString();
      } else {
         this.message = this.error;
      }
   }
}
Example #11
Source File: list-item-tag.component.ts    From angular-component-library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * [ListItemTag Component](https://brightlayer-ui-components.github.io/angular/?path=/info/components-list-item-tag--readme)
 *
 * The `<blui-list-item-tag>` is a text item with a colored background and rounded corners that is used to tag lists.
 */
@Component({
    selector: 'blui-list-item-tag',
    templateUrl: './list-item-tag.component.html',
    styleUrls: ['./list-item-tag.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    encapsulation: ViewEncapsulation.None,
    host: {
        class: 'blui-list-item-tag',
    },
})
export class ListItemTagComponent implements OnChanges {
    /** Color of the label background */
    @Input() backgroundColor: string;
    /** Color of the label text */
    @Input() fontColor: string;
    /** The label text */
    @Input() label: string;

    ngOnChanges(): void {
        requireInput<ListItemTagComponent>(['label'], this);
    }
}
Example #12
Source File: cometchat-ban-group-member-list.component.ts    From cometchat-pro-angular-ui-kit with MIT License 6 votes vote down vote up
@Component({
  selector: "cometchat-ban-group-member-list",
  templateUrl: "./cometchat-ban-group-member-list.component.html",
  styleUrls: ["./cometchat-ban-group-member-list.component.css"],
})
export class CometChatBanGroupMemberListComponent implements OnInit,OnChanges {
  @Input() item = null;
  @Input() member: any = null;
  @Input() loggedInUser = null;
  @Output() actionGenerated: EventEmitter<any> = new EventEmitter();

  name: string = '';
  banIcon = BAN_ICON;

  constructor() {}
  ngOnChanges(changes: SimpleChanges){
  
   
  }

  ngOnInit() {}

  /**
   * propagates and action to unaban the current member
   */
  unbanMember() {
    try {
      this.actionGenerated.emit({
        type: enums.UNBAN,
        payLoad: { member: this.member },
      });
    } catch (error) {
      logger(error);
    }
  }
}
Example #13
Source File: dxc-button-icon.component.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
@Component({
    selector: "dxc-button-icon",
    templateUrl: "./dxc-button-icon.component.html",
  })
  export class DxcButtonIconComponent implements OnChanges {
  
    constructor() {}
  
    public ngOnChanges(): void {
      
    }
  
  }
Example #14
Source File: member-details-card.component.ts    From dating-client with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-member-details-card',
  templateUrl: './member-details-card.component.html',
  styleUrls: [ './member-details-card.component.scss' ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MemberDetailsCardComponent implements OnChanges {

  interests: string[] | undefined = [];

  colors = [ 'primary', 'danger', 'info', 'success' ];

  locationIcon = faMapMarkerAlt as IconProp;
  calendarIcon = faCalendarAlt as IconProp;

  @Input() user!: User & Status;

  ngOnChanges() {
    this.interests = this.user?.interests?.split(',');
  }

  getCover() {
    return {
      'background-image': `
        linear-gradient(0, #000000e8 10%, #6b0fc02b 50%),
        url(https://i.imgur.com/t6xCnGT.jpg)`
    };
  }

  getProfilePicture() {
    if (this.user?.photoUrl) {
      return { 'background-image': `url(${ this.user.photoUrl })` };
    }
    return { 'background-image': `url(https://i.imgur.com/bLrOP4M.png)` };
  }

}
Example #15
Source File: base.component.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
@Component({
  selector: 'wc-base',
  template: `<div></div>`,
})
export class BaseComponent implements OnChanges {
  @Input() apiUrl = '/'
  @Input() searchId: string
  @Input() primaryColor = '#9a9a9a'
  @Input() secondaryColor = '#767676'
  @Input() mainColor = '#1a1a1a'
  @Input() backgroundColor = '#cecece'

  isInitialized = false
  facade: SearchFacade
  translate: TranslateService

  constructor(private injector: Injector) {
    this.facade = injector.get(SearchFacade)
    this.translate = injector.get(TranslateService)
  }

  ngOnChanges(): void {
    if (!this.isInitialized) {
      apiConfiguration.basePath = this.apiUrl
      this.translate.reloadLang(this.translate.currentLang)
      ThemeService.applyCssVariables(
        this.primaryColor,
        this.secondaryColor,
        this.mainColor,
        this.backgroundColor
      )
      this.isInitialized = true
      this.facade.init(this.searchId)
    }
  }
}
Example #16
Source File: viewer.component.ts    From open-source with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-docs-viewer',
  templateUrl: './viewer.component.html',
  styleUrls: ['./viewer.component.styl'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ViewerComponent implements OnChanges {
  @Input() source: string;

  @ViewChild('content', { read: ElementRef, static: true }) container: ElementRef;

  loadExamples = false;

  get lang(): string {
    return this.route.snapshot.queryParams.lang || this.i18n.lang;
  }

  constructor(
    private route: ActivatedRoute,
    private content: ContentService,
    private i18n: I18nService,
  ) {}

  ngOnChanges(): void {
    if (this.source) {
      // render the markdown content
      this.render(this.source);
    }
  }

  private render(markdown: string, decodeHtml = false): void {
    let compiled = this.content.compile(markdown, decodeHtml);
    this.container.nativeElement.innerHTML = compiled;
    this.content.highlight(this.container.nativeElement);
  }
}
Example #17
Source File: highlight.directive.ts    From open-genes-frontend with Mozilla Public License 2.0 6 votes vote down vote up
@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective implements OnChanges {
  @Input('highlightText') searchTerm: string;
  @Input() caseSensitive = false;
  @Input() customClasses = '';

  @HostBinding('innerHtml')
  content: string;
  constructor(private el: ElementRef, private sanitizer: DomSanitizer) {}

  ngOnChanges(changes: SimpleChanges) {
    if (this.el?.nativeElement) {
      if ('searchTerm' in changes || 'caseSensitive' in changes) {
        const text = (this.el.nativeElement as HTMLElement).textContent;
        if (this.searchTerm === '') {
          this.content = text;
        } else {
          const regex = new RegExp(this.searchTerm, this.caseSensitive ? 'g' : 'gi');
          const newText = text.replace(regex, (match: string) => {
            return `<mark class="text-highlight">${match}</mark>`;
          });
          const sanitzed = this.sanitizer.sanitize(SecurityContext.HTML, newText);
          this.content = sanitzed;
        }
      }
    }
  }
}
Example #18
Source File: tutorial-dialog.component.ts    From bdc-walkthrough with MIT License 5 votes vote down vote up
@Component({
  selector: 'bdc-walk-dialog',
  templateUrl: './tutorial-dialog.component.html',
  styleUrls: ['./tutorial-dialog.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class BdcWalkDialogComponent implements AfterContentInit, OnDestroy, OnChanges {
  @Input() name: string;
  @Input() mustCompleted: { [taskName: string]: any | boolean } = {};
  @Input() mustNotDisplaying: string[] = [];
  @Input() width = '500px';
  @Output() opened = new EventEmitter<void>();
  @Output() closed = new EventEmitter<void>();
  @ViewChild(TemplateRef, {static: true}) templateRef: TemplateRef<any>;

  dialogRef: MatDialogRef<any>;
  componentSubscription: Subscription;

  constructor(private dialog: MatDialog,
              private tutorialService: BdcWalkService) { }

  ngAfterContentInit() {
    this.componentSubscription = this.tutorialService.changes.subscribe(() => this._sync());
  }

  ngOnChanges(): void {
    this._sync();
  }

  ngOnDestroy() {
    if (this.componentSubscription) {
      this.componentSubscription.unsubscribe();
    }

    this._close();
  }

  getValue(taskName: string): any {
    return this.tutorialService.getTaskCompleted(taskName);
  }

  close(setTasks: { [taskName: string]: any | boolean } = {}) {
    this.tutorialService.logUserAction(this.name, BdcDisplayEventAction.UserClosed);
    this.tutorialService.setTaskCompleted(this.name);
    this.tutorialService.setTasks(setTasks);
  }

  private _open() {
    this.dialogRef = this.dialog.open(this.templateRef, {width: this.width, disableClose: true, restoreFocus: false, panelClass: 'bdc-walk-dialog'});
    this.opened.emit();
  }

  private _close() {
    if (this.dialogRef) {
      this.dialogRef.close();
      this.dialogRef = null;
      this.closed.emit();
    }
  }

  private _sync() {
    if (this.name) {
      if (!this.tutorialService.getTaskCompleted(this.name) &&
        !this.tutorialService.disabled &&
        this.tutorialService.evalMustCompleted(this.mustCompleted) &&
        this.tutorialService.evalMustNotDisplaying(this.mustNotDisplaying)) {

        if (!this.dialogRef) {
          this._open();
          this.tutorialService.setIsDisplaying(this.name, true);
        }
      } else if (this.dialogRef) {
        this._close();
        this.tutorialService.setIsDisplaying(this.name, false);
      }
    }
  }
}
Example #19
Source File: rotating-icon.component.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Rotating icon with smooth rotation completion.
 */
@Component({
  selector: 'app-rotating-icon',
  templateUrl: './rotating-icon.component.html',
  styleUrls: ['./rotating-icon.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [TuiDestroyService]
})
export class RotatingIconComponent implements OnChanges {
  /**
   * Icon image source. Default is reload arrows.
   */
  @Input() image = 'assets/images/icons/reload.svg';

  /**
   * Should rotate image.
   */
  @Input() rotating = false;

  /**
   * Should disable button.
   */
  @Input() disabled = false;

  /**
   * Emits when user clicks on the icon-button.
   */
  @Output() iconClick = new EventEmitter<void>();

  @ViewChild('icon', { static: true }) icon: ElementRef;

  public stopAnimation: 'rotating' | 'graduallyStop' | 'stopped' = 'stopped';

  constructor(@Inject(WINDOW) private window: Window) {}

  ngOnChanges(changes: NgChanges<RotatingIconComponent>) {
    if (changes.rotating?.currentValue && !changes.rotating?.previousValue) {
      this.animate();
    }
  }

  private animate(): void {
    const start = performance.now();
    const roundTime = 1000;
    const degAtMs = 360 / roundTime;
    let animationIteration = 0;

    const animationCallback = (time: number) => {
      const currentTime = time > start ? time - start : 0;
      const currentAngle = Math.round((currentTime * degAtMs) % 360);
      const currentIteration = Math.floor((currentTime * degAtMs) / 360);

      if (!this.rotating && currentIteration > animationIteration) {
        this.setIconRotation(0, 'left');
        return;
      }

      animationIteration = currentIteration;
      this.setIconRotation(currentAngle, 'left');
      this.window.requestAnimationFrame(animationCallback);
    };

    this.window.requestAnimationFrame(animationCallback);
  }

  private setIconRotation(deg: number, direction: 'right' | 'left' = 'right'): void {
    deg = direction === 'left' ? deg * -1 : deg;
    this.icon.nativeElement.style.transform = `rotate(${deg}deg)`;
  }

  public onClick(): void {
    this.iconClick.emit();
  }
}
Example #20
Source File: col.component.ts    From ng-devui-admin with MIT License 5 votes vote down vote up
@Component({
  selector: 'da-col-item',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <ng-content></ng-content>
  `,
})
export class ColComponent implements OnInit, OnChanges {

  @HostBinding('class.da-col') daCol = true;

  @Input() daSpan: number;
  @Input() daMs: number | DaMergedProperty;
  @Input() daMm: number | DaMergedProperty;
  @Input() daMl: number | DaMergedProperty;
  @Input() daXs: number | DaMergedProperty;
  @Input() daSm: number | DaMergedProperty;
  @Input() daMd: number | DaMergedProperty;
  @Input() daLg: number | DaMergedProperty;
  @Input() daXl: number | DaMergedProperty;

  @Input() daOrder: number;
  @Input() daOrderMs: number;
  @Input() daOrderMn: number;
  @Input() daOrderMl: number;
  @Input() daOrderXs: number;
  @Input() daOrderSm: number;
  @Input() daOrderMd: number;
  @Input() daOrderLg: number;
  @Input() daOrderXl: number;

  @Input() daOffset: number;
  @Input() daOffsetMs: number;
  @Input() daOffsetMn: number;
  @Input() daOffsetMl: number;
  @Input() daOffsetXs: number;
  @Input() daOffsetSm: number;
  @Input() daOffsetMd: number;
  @Input() daOffsetLg: number;
  @Input() daOffsetXl: number;

  @Input() daAlignSelf: DaAlignSelf;
  @Input() daAlignSelfMs: DaAlignSelf;
  @Input() daAlignSelfMm: DaAlignSelf;
  @Input() daAlignSelfMl: DaAlignSelf;
  @Input() daAlignSelfXs: DaAlignSelf;
  @Input() daAlignSelfSm: DaAlignSelf;
  @Input() daAlignSelfMd: DaAlignSelf;
  @Input() daAlignSelfLg: DaAlignSelf;
  @Input() daAlignSelfXl: DaAlignSelf;

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
  ) { }

  ngOnInit(): void {
    setGridClass(this, this.elementRef, this.renderer);
  }

  ngOnChanges(): void {
    setGridClass(this, this.elementRef, this.renderer);
  }
}
Example #21
Source File: brand-icons.stories.ts    From canopy with Apache License 2.0 5 votes vote down vote up
@Component({
  selector: 'lg-swatch-brand-icon',
  template: `
    <div class="swatch" *ngFor="let icon of icons; let i = index">
      <lg-brand-icon
        class="swatch__svg"
        [name]="icon.name"
        [size]="size"
        [colour]="i === 0 ? colour : null"
        [attr.style]="cssVar"
      ></lg-brand-icon>
      <span class="swatch__name">{{ icon.name }}</span>
    </div>
  `,
  styles: [
    `
      :host {
        display: flex;
        flex-wrap: wrap;
      }

      .swatch {
        margin: var(--space-md);
        flex: 0 0 8rem;
      }

      .swatch__name {
        display: block;
        text-align: center;
        margin-top: var(--space-xxs);
      }

      .swatch__svg {
        display: block;
        margin: 0 auto;
      }
    `,
  ],
})
class SwatchBrandIconComponent implements OnChanges {
  @Input() size: string;
  @Input() colour: string;
  @Input() globalColour: string;

  icons = lgBrandIconsArray;
  cssVar: SafeStyle;

  constructor(private registry: LgBrandIconRegistry, private sanitizer: DomSanitizer) {
    this.registry.registerBrandIcon(this.icons);
  }

  ngOnChanges({ globalColour }: SimpleChanges) {
    if (globalColour && globalColour.currentValue) {
      this.cssVar = this.sanitizer.bypassSecurityTrustStyle(
        `--brand-icon-fill-primary: var(${globalColour.currentValue})`,
      );
    }
  }
}
Example #22
Source File: user-edit.component.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent implements OnInit, OnChanges {

  @Input()
  member: MemberEntity;

  @Output()
  saveEvent: EventEmitter<MemberEntity> = new EventEmitter();

  editForm: FormGroup;
  idControl: FormControl;
  loginControl: FormControl;
  avatarControl: FormControl;

  constructor(private fb: FormBuilder) {
    this.createEditForm();
  }

  ngOnInit(): void {
  }

  ngOnChanges(): void {
    this.editForm.patchValue(this.member);
  }

  createEditForm() {
    this.editForm = this.fb.group({
      id: ['', Validators.required],
      login: ['', [Validators.required, Validators.minLength(6)]],
      avatar_url: ''
    });

    this.idControl = this.editForm.get('id') as FormControl;
    this.loginControl = this.editForm.get('login') as FormControl;
    this.avatarControl = this.editForm.get('avatar_url') as FormControl;
  }

  handleEditFileInput(files: FileList) {
    const reader = new FileReader();
    reader.readAsDataURL(files[0]);
    reader.onload = (event) => {
      this.avatarControl.setValue(reader.result);
    };
  }

  save() {
    const member = this.editForm.value;
    this.saveEvent.emit(member);
  }
}
Example #23
Source File: inlineTest.c.ts    From ngx-dynamic-hooks with MIT License 5 votes vote down vote up
@Component({
  selector: 'dynhooks-inlinetest',
  templateUrl: './inlineTest.c.html',
  styleUrls: ['./inlineTest.c.scss'],
})
export class InlineTestComponent implements OnDynamicMount, OnDynamicChanges, DoCheck, OnInit, OnChanges, AfterViewInit, OnDestroy {
  @Input() backgroundColor: string = '#25436c';
  @Input() nr!: number;
  @Input() config: any;
  mountContext: any;
  mountContentChildren!: Array<DynamicContentChild>;
  changesContext: any;
  changesContentChildren!: Array<DynamicContentChild>;

  constructor(private cd: ChangeDetectorRef) {
  }

  ngOnInit () {
    // console.log('textbox init');
  }

  ngOnChanges(changes: any) {
    // console.log('textbox changes');
  }

  ngDoCheck() {
    // console.log('textbox doCheck');
  }

  ngAfterViewInit() {
    // console.log('textbox afterviewinit');
  }

  ngOnDestroy() {
    // console.log('textbox destroy');
  }

  onDynamicMount(data: OnDynamicData) {
    this.mountContext = data.context;
    this.mountContentChildren = (data as any).contentChildren;
  }

  onDynamicChanges(data: OnDynamicData) {
    if (data.hasOwnProperty('context')) {
      this.changesContext = data.context;
    }
    if (data.hasOwnProperty('contentChildren')) {
      this.changesContentChildren = (data as any).contentChildren;
    }
  }

}
Example #24
Source File: proof-item.component.ts    From mylog14 with GNU General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-proof-item',
  templateUrl: './proof-item.component.html',
  styleUrls: ['./proof-item.component.scss'],
})
export class ProofItemComponent implements OnInit, OnChanges {
  @Input() status: ProofStatus;

  proofStatus = ProofStatus;
  private readonly display = new BehaviorSubject<ProofDisplay>(this.getProofDisplay(ProofStatus.LOADING));
  display$: Observable<ProofDisplay> = this.display;

  constructor() { }

  ngOnInit() { }

  ngOnChanges(changes: SimpleChanges) {
    this.display.next(this.getProofDisplay(changes.status.currentValue as ProofStatus));
  }

  private getProofDisplay(status: ProofStatus): ProofDisplay {
    switch (status) {
      case ProofStatus.LOADING:
        return {
          icon: 'shield-outline',
          color: 'black',
        };
      case ProofStatus.COMPLETE:
        return {
          icon: 'shield-checkmark-outline',
          color: 'primary',
        };
      default:
        return {
          icon: 'alert-circle-outline',
          color: 'danger',
        };
    }
  }
}
Example #25
Source File: chat-messages.component.ts    From Angular-Cookbook with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-chat-messages',
  templateUrl: './chat-messages.component.html',
  styleUrls: ['./chat-messages.component.scss'],
})
export class ChatMessagesComponent implements OnInit, OnChanges {
  @ViewChild('messagesList') private messagesList: ElementRef;
  @Input('messages') public messages: Array<Message>;
  constructor() {}

  ngOnInit() {
    this.scrollToBottom(); // scroll to bottom on component init
  }

  ngOnChanges(changes: SimpleChanges) {
    if (!changes.messages || changes.messages.isFirstChange()) {
      return;
    }
    if (!(changes.messages.previousValue && changes.messages.currentValue)) {
      return;
    }
    if (
      changes.messages.previousValue.length ===
      changes.messages.currentValue.length
    ) {
      return;
    }
    this.scrollToBottom(); // whenever the change detection happens. I.e. messages are changed.
  }

  removeMessage(message) {
    this.messages.splice(this.messages.indexOf(message), 1);
  }

  /**
   * @author Ahsan Ayaz
   * Scrolls to bottom
   */
  scrollToBottom() {
    try {
      setTimeout(() => {
        this.messagesList.nativeElement.scrollTop = this.messagesList.nativeElement.scrollHeight;
      }, 0);
    } catch (err) {
      console.log(err);
    }
  }
}
Example #26
Source File: dependent-intentions.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
@Component({
  selector: 'devtools-dependent-intentions',
  templateUrl: './dependent-intentions.component.html',
  styleUrls: ['./dependent-intentions.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DependentIntentionsComponent implements OnChanges {

  private _appChange$ = new ReplaySubject<void>(1);

  @Input()
  public appSymbolicName: string;

  public intentionsByApp$: Observable<Map<string, Intention[]>>;
  public filterFormControl = new FormControl();

  constructor(manifestService: DevToolsManifestService, private _router: Router) {
    this.intentionsByApp$ = this._appChange$
      .pipe(
        switchMap(() => manifestService.observeDependentIntentions$(this.appSymbolicName)),
        expand(intentions => this.filterFormControl.valueChanges.pipe(take(1), map(() => intentions))),
        map(intentions => filterManifestObjects(intentions, this.filterFormControl.value)),
        map(intentions => intentions.reduce((acc, intention) => Maps.addListValue(acc, intention.metadata.appSymbolicName, intention), new Map())),
      );
  }

  public ngOnChanges(changes: SimpleChanges): void {
    this.filterFormControl.reset('');
    this._appChange$.next();
  }

  public onOpenAppClick(event: MouseEvent, appSymbolicName: string): void {
    event.stopPropagation();
    this._router.navigate(['/apps', {outlets: {details: [appSymbolicName]}}]);
  }

  public trackByApplicationFn(index: number, entry: KeyValue<string, Intention[]>): string {
    return entry.key;
  }

  public trackByIntentionFn(index: number, intention: Intention): string {
    return intention.metadata.id;
  }
}
Example #27
Source File: field.component.ts    From colo-calc with Do What The F*ck You Want To Public License 5 votes vote down vote up
@Component({
  selector: 'app-field',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.scss']
})
export class FieldComponent implements OnInit, OnChanges {
  @Input() public matrix: Array<Tile> = [];
  // @TODO: change
  @Input() public doClears = false;

  constructor(
    private lineService: LineService
  ) { }

  ngOnInit() {
  }

  public drawLines() {
    if (this.doClears) {
      this.lineService.clearLines();
    }
    this.matrix.forEach((tile) => {
      if (tile.targets) {
        this.lineService.createLine(
          'tile' + tile.id,
          'tile' + tile.targets.id,
          tile.lineColour
        )
      }
      if (tile.summonTargets) {
        this.lineService.createLine(
          'tile' + tile.id,
          'tile' + tile.summonTargets.id,
          tile.summonLineColour,
          true
        )
      }
    });
  }
 
  public ngOnChanges(changes: SimpleChanges): void {
    try {
      this.drawLines();
    } catch (error) {
      console.error(error)
      try {
        setTimeout(() => this.drawLines(), 100);
      } catch (error) {
        console.error('We tried :(', error)
      }
    }
  }
}
Example #28
Source File: formatter.directive.ts    From svg-path-editor with Apache License 2.0 5 votes vote down vote up
@Directive({
  selector: '[appFormatter]'
})
export class FormatterDirective implements OnChanges {
  @Input() formatterType: 'float'|'positive-float'|'integer'|'positive-integer' = 'float';
  @Input() value: number = 0;
  @Output() valueChange = new EventEmitter<number>();
  internalValue: number = 0;

  constructor(private el: ElementRef<HTMLInputElement>) { }

  private get viewValue(): string {
    return this.el.nativeElement.value;
  }

  private set viewValue(newValue: string) {
    if (this.viewValue !== newValue) {
      this.el.nativeElement.value = newValue;
    }
  }

  @HostListener('blur', ['$event'])
  onBlur(e: FocusEvent) {
    if (this.internalValue !== parseFloat(this.viewValue)) {
      this.viewValue = formatNumber(this.internalValue, 4);
    }
  }

  @HostListener('input', ['$event'])
  onInput(e: InputEvent) {
    let value = '';
    if (this.formatterType === 'float') { value = this.viewValue.replace(/[\u066B,]/g, '.').replace(/[^\-0-9.eE]/g, ''); }
    if (this.formatterType === 'integer') { value = this.viewValue.replace(/[^\-0-9]/g, ''); }
    if (this.formatterType === 'positive-float') { value = this.viewValue.replace(/[\u066B,]/g, '.').replace(/[^0-9.eE]/g, ''); }
    if (this.formatterType === 'positive-integer') { value = this.viewValue.replace(/[^0-9]/g, ''); }

    this.viewValue = value;
    const floatValue = parseFloat(value);
    if (!isNaN(floatValue)) {
      this.valueChange.emit(floatValue);
      this.internalValue = floatValue;
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.value) {
      if (changes.value.currentValue !== parseFloat(this.viewValue)) {
        this.viewValue = formatNumber(changes.value.currentValue, 4);
        this.internalValue = changes.value.currentValue;
      }
    }
  }
}
Example #29
Source File: sort.directive.ts    From alauda-ui with MIT License 5 votes vote down vote up
@Directive({
  selector: '[auiSort]',
  exportAs: 'auiSort',
})
export class SortDirective implements OnChanges, OnDestroy {
  sortables = new Map<string, Sortable>();

  readonly _stateChanges = new Subject<void>();

  @Input()
  active: string;

  @Input()
  start: 'asc' | 'desc' = 'asc';

  @Input()
  get direction(): SortDirection {
    return this._direction;
  }

  set direction(direction: SortDirection) {
    if (
      isDevMode() &&
      direction &&
      direction !== 'asc' &&
      direction !== 'desc'
    ) {
      throw getSortInvalidDirectionError(direction);
    }
    this._direction = direction;
  }

  private _direction: SortDirection = '';

  @Output()
  readonly sortChange: EventEmitter<Sort> = new EventEmitter<Sort>();

  register(sortable: Sortable): void {
    if (!sortable.id) {
      throw getSortHeaderMissingIdError();
    }

    if (this.sortables.has(sortable.id)) {
      throw getSortDuplicateSortableIdError(sortable.id);
    }

    this.sortables.set(sortable.id, sortable);
  }

  deregister(sortable: Sortable): void {
    this.sortables.delete(sortable.id);
  }

  sort(sortable: Sortable): void {
    if (this.active !== sortable.id) {
      this.active = sortable.id;
      this.direction = sortable.start ? sortable.start : this.start;
    } else {
      this.direction = this.direction === 'asc' ? 'desc' : 'asc';
    }

    this.sortChange.emit({
      active: this.active,
      direction: this.direction,
    });
  }

  ngOnChanges() {
    this._stateChanges.next();
  }

  ngOnDestroy() {
    this._stateChanges.complete();
  }
}