Skip to content

Instantly share code, notes, and snippets.

@danielkuhlwein
Last active June 13, 2018 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkuhlwein/a766e763f9d1e05f1df3543dd5a775b5 to your computer and use it in GitHub Desktop.
Save danielkuhlwein/a766e763f9d1e05f1df3543dd5a775b5 to your computer and use it in GitHub Desktop.
Content Header Logic
@Component({
selector: 'ss-content-header',
templateUrl: './content-header.component.html'
})
export class ContentHeaderComponent implements OnInit {
@Input() editing: boolean;
@Input() status: string;
matInputs: HTMLCollectionOf<Element>;
constructor(@Inject(DOCUMENT) private document: Document,
@Inject(WINDOW) private window: Window) { }
ngOnInit(): void {
// Dynamically set all inputs to the width of their content
this.setInputWidthsToContent();
}
/**
* Sets all input widths to match their text content
*/
setInputWidthsToContent() {
// Get all inputs in card
this.matInputs = this.document.getElementsByClassName('mat-form-field');
// For each input, set width of input to length of content
for (let i = 0; i < this.matInputs.length; i++) {
const matInput = this.matInputs[i];
const inputs = matInput.getElementsByTagName('input');
// Only set width for matInputs with textInput
if (inputs.length !== 0) {
const newValue = inputs[0].value; // will only be one input under matInput
this.resizeInputWidth(matInput, newValue);
}
}
}
/**
* Calls the resizeInputWidth whenever an input value is changed
* @param event The input Element being called from
* @param newValue the input's new value as a string
*/
onInputChange(event: Event, newValue: string) {
console.log(event);
// Need to outnest by 4 to target the mat-form-field element
const matInput = event.srcElement.parentElement.parentElement.parentElement.parentElement;
this.resizeInputWidth(matInput, newValue);
}
/**
* Resizes a particular mat-form-field input to match its content
* @param matInput The mat-form-field Element that needs to be resized
* @param newValue The new value that will be longer or shorter than before
*/
resizeInputWidth(matInput: Element, newValue: string) {
// Cannot access properties unless element has id?
// Set the id
matInput.id = '2FvZXR';
const contentLength = newValue.length;
// assumes pixel width of each character is 8px
const inputWidth = (contentLength + 1) * 8;
// Apply the style (setting width of matInput to fit width of textInput)
this.document.getElementById('2FvZXR').style.width = inputWidth + 'px';
// Unset the id
matInput.removeAttribute('id');
}
toggleEdit() {
this.editing = !this.editing;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment