简体   繁体   中英

Angular: Show difference between Two Class Components

I have a Parent component. It injects data into two @Input() Child duplicate card components, showing html. In addition, there is difference class in parent, flagging difference between the two classes .

When displaying class members in html below, is there method to highlight items which have changed in, Without Modifying Child Components? Prefer not to inject difference logic in child card components. Would rather have the parent controller highlight differences, without overall logic leaking into child components.

All child components have same css class referring to member name, .city refers to city, .zipcode pertains to item zipcode,

Might need to create javascript function, and then applying in Angular in ngOnit, still researching, trying to apply this answer maybe? Generate dynamic css based on variables angular

在此处输入图片说明

export class PropertyLocation {   
    streetName: string;
    streetType: string;
    postdirectional?: string;
    unitNumber?: string;
    unitType?: string;
    city: string;
    state?: string;
    zipcode: number;

    effectiveStartDate: Date;
    addressChangeReason?: AddressChangeReasonDto;
    addressSource?: SourceOfAddressDto;
}

Difference class: feel free to restructure class in parent, to make solution easier if required

export class DifferenceClass {   
    ClassMember: string;
    DifferentFlag: boolean;
}

derived from

function isSame(obj1:any, obj2:any): DifferenceClass {
   let difference: DifferenceClass[];
   for (const key in obj1) {
     if (obj1[key] !== obj2[key]) {
       differences.push(new DifferenceClass(key,true));
     }
     else 
       differences.push(new DifferenceClass(key,false));
   }
   return differences;
 }

A custom Directive is helpful to separate some UI logic from the Component class.

Example:

@Directive({
  selector: '[highlighter]',
})

@Input('streetName') streetName: string;

export class HighlighterDirective {
  constructor(private host: ElementRef,
              private rd: Renderer2) {}
} 

ngOnChanges(changes: SimpleChanges) {
  if (changes['streetName'].currentValue != changes['streetName'].previousValue) {
    this.rd.setStyle(this.host.nativeElement, 'color', 'red')
  }
}

ps code is completely from my memory, could be some types, syntax errors. But you get the idea - Directive has access to the same inputs defined on the component:

<custom-component [streetName] highlighter></custom-component>

Then you can use ngOnChanges or other technique to distinguish when the property has changed its value and use Renderer2 (for the best practices), to apply direct changes to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM